简体   繁体   中英

Python Class Attributes default

class A():
    count = 0
    print(count)
    def __init__(self):
        A.count+=1
    def exclaim(self):
        print("I'm an A")
    @classmethod
    def kids(cls):
        print("A has", cls.count,"little objects.")

My question is that I create a object with "t1=A()". And A.count should be 1. I understand. And then, if I create second object with "t2=A()". I don't understand why A.count = 2. I thought when used A(), it will make count back to default 0.

In A , count is a class variable, meaning there is one copy of the variable for the class. Instances of the class continue to pick up that value.

In __init__ , you have A.count += 1 . This modifies the class variable directly, without creating an instance variable. So there's still only one copy of count , and all instances pick up the current value.

If you instead change it to self.count += 1 , then you'll get the behavior you expect. Initially, each instance will pick up the value from the class. But when self.count += 1 is executed, it will add 1 to count and then store the result in an instance variable that is private to the instance. Thereafter, the instance will have its own copy of count which is independent from the class variable, or the instance variables in other instances of the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM