i have a question about class attribute in python.
class base :
def __init__ (self):
pass
derived_val = 1
t1 = base()
t2 = base()
t2.derived_val +=1
t2.__class__.derived_val +=2
print t2.derived_val # its value is 2
print t2.__class__.derived_val # its value is 3
The results are different. I also use id() function to find t2.derived_val and t2.__class__.derived_val have different memory address.
My problem is derived_val is class attribute. Why it is different in above example?
Is it because the instance of class copy its own derived_val beside the class attribute?
There are class attributes, and instance attributes.
When you say
You are defining a class attribute.
derived_valbecomes a key inbase.__dict__.When you say
t2.derived_valPython tries to find ‘derived_val’ int2.__dict__. Since it is not there, it looks if there is a'derived_val'key in any oft2‘s base classes.But when you assign a value to
t2.derived_val, you are now adding an instance attribute tot2. Aderived_valkey is added tot2.__dict__.Note that at this point, there are two
derived_valattributes, but onlythe instance attribute is easily accessible. The class attribute becomes accessible only through referencing
base.derived_valor direct access to the class dictbase.__dict__.