[英]What is the difference between class and data attributes?
To quote diveintopython, 引用diveintopython,
"You already know about data attributes, which are variables owned by a specific instance of a class. Python also supports class attributes, which are variables owned by the class itself."
“您已经知道数据属性,它们是类的特定实例所拥有的变量。Python还支持类属性,它们是由类本身拥有的变量。”
In what sense are class attributes owned by a class? 从什么意义上讲,一个类拥有类属性? If you change the value of a class attribute in a specific instance, that change is only reflected in that instance (and not in other instances of the class).
如果您在特定实例中更改类属性的值,则该更改仅反映在该实例中(而不在类的其他实例中)。
From my vantage point this makes class attributes fundamentally the same as data (ie instance) attributes (notwithstanding the syntactic differences). 从我的角度来看,这使类属性与数据(即实例)属性基本相同(尽管在语法上有所不同)。
In C++ change the value of a "class variable", and that change is reflected in all instances. 在C ++中,更改“类变量”的值,并且该更改将反映在所有实例中。
What is the difference between the two? 两者有什么区别?
I think that this example will explain the meaning to you. 我认为该示例将向您解释其含义。
class A(object):
bar = 1
a = A()
b = A()
b.bar = 2
print a.bar # outputs 1
A.bar = 3
print a.bar # outputs 3
print b.bar # outputs 2
In this case b.bar
will be owned by instance after b.bar = 2
but a.bar
will still be owned by class. 在这种情况下,
b.bar
将在b.bar = 2
之后由实例拥有,但a.bar
仍将由类拥有。 That is why it will be changed on instance after changing it on class and b.bar
will not. 这就是为什么在类上对其进行更改后它将在实例上进行更改,而
b.bar
将不会进行更改的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.