Class variables and instance variables in Python
One, don't talk much, code first
class A:
aa = 1
def __init__(self,x,y):
self.x = x
self.y = y
a = A(2,3)
print(a.x, a.y, a.aa) # 2,3,1
print(A.aa) # 1
print(A.x) # AttributeError:type object ‘A’ has no attribute ‘x’
Among them aa
is a class variable. The __init__()
constructor is initialized in the class first , and the first parameter passed in self
refers to an instance of the class. The parameters passed in x,y
also instantiate the parameters of the object.
Two, attribute modification
The following content is based on the initial code above
a = A(2,3)
A.aa = 11
print(a.x, a.y, a.aa) # 2,3,11
print(A.aa) # 11
After modifying the class variable, the attributes of the related instance object lookup will also change ( a.aa
also become 11
).
a = A(2,3)
A.aa = 11
a.aa = 100
print(a.x, a.y, a.aa) # 2,3,100
print(A.aa) # 11
a.aa = 100
After adding , it was found that only a.aa
changed, A.aa
or 11
that the properties in the class did not change.
When the assignment statement operates on the instantiated object, the class variable will not change; and because a
there is no aa
attribute (variable) in a.aa = 100
the instance object , it will a
create a new aa
attribute (variable) for the instance object and assign it 100
.
a = A(2,3)
A.aa = 11
a.aa = 100
print(a.x, a.y, a.aa) # 2,3,100
print(A.aa) # 11
b = A(3,5)
print(b.aa) # 11
When instantiating an b
object, I found that it b.aa
was not 100
( a.aa
), but the previous 11
( A.aa
). In fact, the class variables in object A (class) are shared by all instance objects.
Subsection
-
Class variables and instance variables are independent of each other
-
Use the assignment statement on the instance to create a new attribute (variable)