简体   繁体   中英

What is the difference between class and data attributes?

To quote 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."

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.

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. That is why it will be changed on instance after changing it on class and b.bar will not.

This question is a duplicate of this one :

>>> class B(object):
...     foo = 1
... 
>>> b = B()
>>> b.__dict__
{}
>>> b.foo = 2
>>> b.__dict__
{'foo': 2}

When you assign a value to b , you add an instance variable; you're not modifying the class attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM