如何更改__init__中的类属性?

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.我该如何工作?

omr*_*don 6

变更countAnt.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)

  • @martineau不,self.count将是一个实例变量 - 这非常具体_not_ OP想要什么.他们想要一个类变量,因此Ant.count是(可能是唯一的)引用它的正确方法. (2认同)
  • 糟糕,是的,你是对的.`self`仅用于读取类变量值,而不用于更改它,这将创建一个实例变量作为副作用(此后隐藏类属性).也就是说,通过在其位置使用`self .__ class__`,仍然可以避免在代码中的所有位置硬编码类名.如果这太长了,可以在方法的开头用`cls = self .__ class__`创建一个局部变量,并在其中使用. (2认同)