What happens when I instantiate a class in Python?

Could you clarify some of the ideas behind Python classes and class instances?

Consider this:

class A():
    name = 'A'

a = A()

a.name = 'B' # point 1 (instance of class A is used here)

print a.name
print A.name

prints:

B
A

if instead point 1i use the class name, the output is different:

A.name = 'B' # point 1 (updated, class A itself is used here)

prints:

B
B

Even if the classes in Python were a kind of prototype for class instances, I would expect the already created instances to remain intact, i.e. are output as follows:

A
B

Can you explain what is really going on?

+3
source share
3 answers

, Python ( ) __init__. , .

Python . , :

class Empty: pass
e = Empty()
e.f = 5
print e.f # shows 5

, :

  • A name, A.
  • A, A.
  • A ( A) B
  • a.name, A.
  • a.name,
+4

, . , Python ( ), . , id (). x is y , .

>>> class A(object):
...     name = 'A'
... 
>>> x = A()
>>> A.name is x.name
True
>>> x.name = 'fred'  # x.name was bound to a new object (A.name wasn't)
>>> A.name is x.name
False
>>> x = A()          # start over
>>> A.name is x.name
True                 # so far so good
>>> A.name = 'fred'
>>> A.name is x.name 
True                 # this is somewhat counter-intuitive
+1
source

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


All Articles