Reputation: 1347
It seems that python class members also are "secretly" copied to instance members, I have never heard of this. Is this described somewhere?
Here is a small example I did to investigate this (python 3.6.7 ubuntu 18:04).
class A:
a = 'hello' # class member
def __init__(self):
print(self.a) # a has also become a instance member
self.a = 'Hi' # change the instance member of a
print(A.a) # class member a unchanged
a = A()
Upvotes: 1
Views: 39
Reputation: 3811
This is not at all a "secret" copy. It is the intended behaviour and for example discussed here in the official reference (3.2. The standard type hierarchy
: "Class instances"):
A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes. [...]
By creating an entry for the attribute in the class instance's dictionary, you shadow the class's attribute entry.
Let's walk through your example step-by-step:
def __init__(self):
print(self.a) # (1.)
self.a = 'Hi' # (2.)
print(A.a) # (3.)
a = 'hello'
, is found.a
in the class instance's attribute dict. Consequently, this attribute is unique to the class instance.Upvotes: 1