Variable Object vs. class

This is a completely theoretical question. Assume the following code:

>>> class C:
...     a = 10
...     def f(self): self.a = 999
...
>>>
>>> C.a
10
>>> c = C()
>>> c.a
10
>>> c.f()
>>> c.a
999

At this point, the class variable C.ais still accessible through the object c?

+3
source share
4 answers

Yes, though c.__class__.aor type(c).a. They are slightly different in the old-style classes (I hope everyone is already dead, but you never know ...) have type()of <type 'instance'>(and __class__work as expected) the style classes are type()identical __class__, except when the object redefines access to the attribute.

+4
source

All class variables are accessible through objects created from this class.

>>> class C:
...     a = 10
...     def f(self): self.a = 999
... 
>>> C.a
10
>>> c = C()
>>> c.a
10
>>> c.f()
>>> c.a
999
>>> c.__class__.a
10
>>> c.a
999
>>> del(c.a) 
>>> c.a
10

, .

+1

, a c, ร  la c.a. 10.

, c.f(), c.a 999, c.a 10. , c.a , , 1000, c.a 999.

, c, a, a, "" "a .

+1

, , a a. :

>>> class Foo(object):
...     a = 10
... 
>>> c = Foo()
>>> c.a
10
>>> c.a = 100  # this doesn't have to be done in a method
>>> c.a   # a is now an instance attribute
100
>>> Foo.a  # that is shadowing the class attribute
10
>>> del c.a  # get rid of the instance attribute
>>> c.a     # and you can see the class attribute again
10
>>> 

The difference is that it exists as a record in Foo.__dict__, and the other exists as a record in c.__dict__. When you turn to instance.attribute, it returns instance.__dict__['attribute']if it exists, and if not, then type(instance).__dict__['attribute']. Then the superclasses of the class are checked, but this gets a little complicated.

But, in any case, the main thing is that it does not have to be this or that. A class and an instance can have different attributes with the same name, because they are stored in two separate dicts.

+1
source

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


All Articles