我对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
结果是不同的。我还使用id()函数找到t2.derived_val和t2。.derived_val 类 具有不同的内存地址。我的问题是派生的_val是类属性。为什么上面的示例不同?是因为类的实例在class属性旁边复制了自己的named_val吗?
有类属性和实例属性。当你说
class base : derived_val = 1
您正在定义一个类属性。derived_val成为的关键 base.__dict__。
derived_val
base.__dict__
t2=base() print(base.__dict__) # {'derived_val': 1, '__module__': '__main__', '__doc__': None} print(t2.__dict__) # {}
当您说t2.derived_valPython尝试在中找到“ derived_val”时t2.__dict__。由于它不存在,因此将检查的'derived_val'任何基t2类中是否存在键。
t2.derived_val
t2.__dict__
'derived_val'
t2
print(t2.derived_val) print(t2.__dict__) # 1 # {}
但是,当您将值分配给时t2.derived_val,您现在要向添加实例属性t2。一derived_val键加入t2.__dict__。
t2.derived_val = t2.derived_val+1 print(t2.derived_val) print(t2.__dict__) # 2 # {'derived_val': 2}
请注意,此时有两个derived_val属性,但是只有实例属性易于访问。只能通过引用base.derived_val或直接访问class dict来访问class属性base.__dict__。
base.derived_val