Discuss / Python / 为什么不能用self.count

为什么不能用self.count

Topic source

Kyrios'

#1 Created at ... [Delete] [Delete and Lock User]

class Student(object):

    count = 0

    def __init__(self, name):

        self.name = name

        sel.count += 1

寂§无痕

#2 Created at ... [Delete] [Delete and Lock User]

我个人认为,self.count应该是实例属性,而Student.count是类属性,并不能等同

#3 Created at ... [Delete] [Delete and Lock User]

如果是self.count 不会错,但没办法实现功能

你可以跑一下,会发现你创多少个实例.count 后都等于1,因为类属性count始终=0,你每创一个实例都是访问了等于0的类属性,然后+1赋给该实例的实例属性

只有用student.self, 每创一个都在之前类属性基础上加一赋给新的实例属性,才能实现功能


  • 1

Reply