On the Sharing of Class Attributes in python

  • 2021-07-06 11:22:23
  • OfStack

I feel that there is something wrong with this understanding, for example.


class Dog(object): 
 
  name = 'dog' 
 
  def init(self): 
 
    self.age = 18
 
d1 = Dog()
 
d2 = Dog()

Here are two examples d1 and d2.


d1.name #  Output  dogd2.name #  Output  dogd1.name = 'abc'
d1.name #  Output  abcd2.name #  Output  dogDog.name #  Output  dog

The reason is that d1.name outputs dog not because this instance shares class attributes, but because this instance does not have dog attributes, so python looks for class attributes. But once you modify d1.name, which is equivalent to binding the name attribute to the d1 instance, d1.name has nothing to do with the class attribute. Since there is no way to share class attributes between instances, because as long as 1 is assigned, it is equivalent to binding attributes, then the meaning of d1.name mentioned above is different from that of d2.name, and their values are different, so it is obvious that their data is not shared.

However, to modify class properties, you should use the


Dog.name = 'new name'

It should not be


dog1.name = 'new name'

Overriding class attributes because instance attributes have the same name is indeed a place that is easy to ignore and make mistakes.


>>> class Dog():
...  name = "dog"
... 
>>> d1 = Dog()
>>> d1.name
'dog'
>>> d2 = Dog()
>>> d2.name
'dog'
>>> Dog.name
'dog'
>>> Dog.name = "a"
>>> d.name
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
>>> d1.name
'a'
>>> d2.name
'a'
>>> 

Related articles: