A static attribute in Python is a variable that belongs to the class itself, not to individual objects created from that class. It’s sometimes called a class attribute.
Defined inside the class, but outside any methods.
Shared by all instances of the class.
Accessed using either ClassName.attribute or object.attribute.
class Dog: # static/class attribute species = "Canis familiaris" def __init__(self, name): self.name = name # instance attribute dog1 = Dog("Rover") dog2 = Dog("Buddy") print(dog1.species) # Canis familiaris print(dog2.species) # Canis familiaris print(Dog.species) # Canis familiaris
class Shape:
width = 5
height = 5
printChar = '#'
def printRow(self, i):
raise NotImplementedError("Will be implemented
by children extending this class")
def print(self):
for i in range(self.height):
self.printRow(i)
Shape class
Has static attributes: width, height, printChar.
Defines printRow() as an abstract method (raises NotImplementedError).
In Python, raise is used to trigger an exception. It tells the program: “Stop normal execution here and signal that something went wrong.”
Defines print() which loops through rows and calls printRow(i).
In your code, self.height
refers to the class attribute height (which is set to 5 in Shape) but accessed through
the object (self).
When you
call self.height, Python first looks for an instance
attribute named height.
If it doesn’t find one, it uses the class
attribute height.
In your example, since you didn’t
set height inside __init__, every object uses the class’s height
= 5.
class Square(Shape):
def printRow(self, i):
print(self.printChar * self.width)
Square class
Implements printRow(i) by printing a full row of printChar repeated width times.
So Square().print() will print a solid square.
class Triangle(Shape):
def printRow(self, i):
# Row i has (i+1) characters
print(self.printChar * (i + 1))
class EqilateralTriangle(Shape):
def printRow(self, i):
spaces = self.width - i - 1
chars = 2 * i + 1
print(" " * spaces + self.printChar * chars)
self.printChar- Python looks for the attribute on the object (
self). - If the object doesn’t have its own, it falls back to the class attribute (
Shape.printChar). - This makes the code flexible: each instance can override
printCharif needed.
printChar- Python will look for a local variable named
printCharinside the method. - Since none exists, it will raise a
NameError. - It won’t automatically use the class attribute unless you explicitly write
Shape.printChar.
沒有留言:
發佈留言