Python has class and data variables. As a java programmer I started out thinking that class variables are static variables and data variables are instance variables. However, that does not appear to be quite right.
Here is my example:
class Shape:
def sides(self):
return self.numSides;
class Pentagon(Shape):
numSides = 5
def __init__(self):
pass
class Square(Shape):
numSides = 4
def __init__(self):
pass
if __name__ == "__main__":
pentagon = Pentagon()
square1 = Square()
square2 = Square()
square2.__class__.numSides
= 42
print pentagon.sides()
print square1.sides()
print square2.sides()
square3 = Square();
square2.numSides = 7
print pentagon.sides()
print square1.sides()
print square2.sides()
print square3.sides()
That code prints out
5
42
42
5
42
7
42
That confuses me. The numSides variable is clearly an instance variable, otherwise square2.numSides = 7 would set the numSides value for square1, square2, and square3. But, it is also clearly a static variable when referred to using square2.__class__.numSides
= 42 because using that does set the variable in all instances of Square.
So is the real answer that numSides is always an instance variable, but __class__ can be used to find all instances of the class and set those variables to a value as well as change the default value for new instances of that class?
That's what it looks like to me, but the description in the Dive Into Python book does not mention anything about that behavior:
http://www.diveintopython.org/object_oriented_framework/class_attributes.htmlStart Free Trial