Class variables and instance variables in Python

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 aais a class variable. The __init__()constructor is initialized in the class first , and the first parameter passed in selfrefers to an instance of the class. The parameters passed in x,yalso 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.aaalso 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 = 100After adding , it was found that only a.aachanged, A.aaor 11that 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 athere is no aaattribute (variable) in a.aa = 100the instance object , it will acreate a new aaattribute (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 bobject, I found that it b.aawas 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)

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106889049