Discuss / Python / 类方法中不能直接调用类属性吗?

类方法中不能直接调用类属性吗?

Topic source

为什么不能直接在 def init(self, name): self.name = name count = count + 1 像这样直接调用类属性中的count ,count定义的时候不是为public吗? 还有个疑问。 class Student(object): count = 0

def __init__(self, name):
    self.name = name
    Student.count = Student.count + 1

    在每次实例化对象的时候,应该都要进Student这个类,那么count不是应该每次都被初始化为0吗?为什么count会自动被覆盖掉?

1、init方法是绑定实例的属性用的,不能调用类属性count 2、每次实例化对象的时候,只需init来为其绑定属性,不会执行类属性部分,即从类属性之后的部分开始运行的

额,感觉这样可以说的通


  • 1

Reply