蟒蛇类属性 [英] python class attribute
问题描述
我有一个关于在Python类属性的问题。
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
结果是不同的。我也使用id()函数来寻找t2.derived_val和T2。类 .derived_val有不同的内存地址。
我的问题是derived_val是类属性。为什么在上面的例子有什么不同?
难道是因为类的实例复制类属性旁边自己的derived_val?
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
class base :
derived_val = 1
您正在定义一个类属性。 derived_val
成为关键基地.__字典__
。
You are defining a class attribute. derived_val
becomes a key in
base.__dict__
.
t2=base()
print(base.__dict__)
# {'derived_val': 1, '__module__': '__main__', '__doc__': None}
print(t2.__dict__)
# {}
当你说 t2.derived_val
的Python试图找到在'derived_val'T2 .__字典__
。由于它不存在,它看起来是否有任何 T2
的基类的'derived_val
键
When you say t2.derived_val
Python tries to find 'derived_val' in t2.__dict__
. Since it is not there, it looks if there is a 'derived_val'
key in any of t2
's base classes.
print(t2.derived_val)
print(t2.__dict__)
# 1
# {}
但是,当你分配一个值 t2.derived_val
,你现在添加实例属性 T2
。 A derived_val
键添加到 T2 .__字典__
。
But when you assign a value to t2.derived_val
, you are now adding an instance attribute to t2
. A derived_val
key is added to 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
或直接访问类字典基地.__字典__
。
Note that at this point, there are two derived_val
attributes, but only
the instance attribute is easily accessible. The class attribute becomes accessible only through referencing base.derived_val
or direct access to the class dict base.__dict__
.
这篇关于蟒蛇类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!