class C:
count=0
a=C()
b=C()
c=C()
print(a.count)
print(b.count)
print(c.count)
c.count+=10
print(c.count)
print(a.count)
print(b.count)
print(C.count)
C.count+=100
print(a.count)
print(b.count)
print(c.count)
0
0
0
10
0
0
0
100
100
10
为什么后来a.count b.count的值都是100 而c.count的值是10
Class attributes are equivalent to static variables in Java and belong to classes.
Because you define the instance attribute of c here c.count+=10.
So print(c.count) is 10
Because c.count+=10 is equivalent to dynamically adding an instance attribute to the instance object c. When printing c.count, the instance attribute will be printed instead of the class attribute
You can watch it step by step.
First instantiate three C class objects.
Print the count value of a, b, c.
This involves the search order of an attribute.
First, check whether the instance has a count value. If it cannot be found, it will search for the upper level. The upper level of the instance is the class. If it is found that there is count in the class attribute, the count here will be output.
c.count += 10
Originally c.count refers to C.count, but now assigning a new value to it is equivalent to the c instance having the count attribute.
Print the count value of a, b, c, C. At this point instance c already has its own count value.
C.count += 100
Change the count value of class C. c has its own count value, and a and b still refer to C's count value.
That’s probably what it looks like.
In one sentence: For static variables of a class, when an instance assigns a value to it, it actually dynamically adds attributes to the instance. It will not have any impact on the static attributes. When static attributes conflict with instance attributes, the order of access to the instance is prioritized. For: instance-》class
https://segmentfault.com/a/11...