我想为子类的每个新实例添加一个单独的数字(从0开始)。我尝试创建一个类变量,并在每次创建新实例时添加+1。但是我不希望这样:
class Subclass(Class):
number = -1
def __init__(self, argument1, argument2):
super().__init__(argument1, argument2)
self.number += 1
def get_number(self):
return self.number
我必须更改什么?这样:
instance = Subclass(argument1, argument2)
instance2 = Subclass(argument1, argument2)
assert instance.get_number() == 0
assert instance2.get_number() == 1
答案 0 :(得分:0)
您需要使用类对象而不是number
来引用类字段self
:
class Counted():
created = 0
def __init__(self):
self.ordinal = Counted.created
Counted.created += 1
assert Counted().ordinal == 0
assert Counted().ordinal == 1
assert Counted().ordinal == 2