Why do some class variables act as static while others do not?

Dictionaries and lists defined directly below the class definition act as static (e.g. this question )
Why aren't other variables like integer?

>>> class Foo(): bar=1 >>> a=Foo() >>> b=Foo() >>> a.bar=4 >>> b.bar 1 >>> class Foo(): bar={} >>> a=Foo() >>> b=Foo() >>> a.bar[7]=8 >>> b.bar {7: 8} 
+6
source share
3 answers

These are all class variables. Except when you assigned a.bar=4 create an instance variable. Basically, Python has an attribute search order. It goes:

 instance -> class -> parent classes in MRO order (left to right) 

So if you have

 class Foo(object): bar = 1 

This is a class variable Foo. As soon as you do

 a = Foo() a.bar = 2 

You have created a new variable on object a named bar . If you look at a.__class__.bar , you will still see 1, but it will be effectively hidden due to the order mentioned above.

The dict you created is at the class level, so it is shared between all instances of this class.

+15
source

When completing a task

 >>> a.bar=4 

you rebuild the name Foo.bar to 4 , which is a new integer instance. On the other hand,

 >>> a.bar[7]=8 

It Foo.bar not rebuild Foo.bar for something else and simply changes the dictionary that the name refers to.

If you do

 >>> a.bar = {7: 8} 

then you will Foo.bar into a new dictionary.

+6
source

Assuming a is an instance of a , and a has the class bar attribute:

  • a.bar = 4 creates an instance attribute of bar , which hides the class bar in the context of a

  • a.bar[4] = 2 only changes the object that is bound to the bar class (provided that it supports indexing)

  • a.bar += 1 - This nasty . If the class bar class class supports the += operation (for example, by implementing __iadd__() ), then it changes in place and no object level attribute is created. Otherwise, this is equivalent to a.bar = a.bar + 1 and a new instance attribute of bar .

+1
source

Source: https://habr.com/ru/post/904966/


All Articles