search

Home  >  Q&A  >  body text

python - class 类的问题

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

PHPzPHPz2786 days ago614

reply all(4)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 10:25:43

    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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:25:43

    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

    In [1]: class C:
       ...:     c= 10
       ...:
    
    In [2]: c = C()
    
    In [3]: c.c
    Out[3]: 10
    
    In [4]: c.c = 1000
    
    In [5]: c.__dict__
    Out[5]: {'c': 1000}
    
    In [6]: c.__class__.__dict__
    Out[6]: {'__doc__': None, '__module__': '__main__', 'c': 10}
    
    In [7]: c.__class__.c
    Out[7]: 10
    
    In [8]:
    

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:25:43

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:25:43

    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...

    reply
    0
  • Cancelreply