isw*_*swg 2 python attributes class
class Ant:
count = 0
def __init__(self):
if count == 0:
self.real = True
else:
self.real = False
count += 1
Run Code Online (Sandbox Code Playgroud)
所以基本上我想要实现的是我只希望这个类的第一个实例具有"真实"属性True,以及后续属性False.我现在知道这会给我一个unboundlocal错误count.我该如何工作?
变更count为Ant.count
作为count类成员(在Ant类的所有实例之间共享)并且不属于特定实例,您应该将它与类名的前缀一起使用.
class Ant:
count = 0
def __init__(self):
if Ant.count == 0:
self.real = True
else:
self.real = False
Ant.count += 1
Run Code Online (Sandbox Code Playgroud)