如何在__init__内更改类属性? [英] How to change a class attribute inside __init__?
本文介绍了如何在__init__内更改类属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Ant:
count = 0
def __init__(self):
if count == 0:
self.real = True
else:
self.real = False
count += 1
所以基本上我想实现的是,我只希望此类的第一个实例的真实"属性为 True
,而随后的属性为 False 代码>.我知道现在这会给我
count
的unboundlocal错误.我该如何进行这项工作?
So basically what I want to achieve is I want only the first instance of this class to have the "real" attribute to be True
, and the subsequent attributes to be False
. I know right now this is going to give me unboundlocal error for count
. How do I make this work?
推荐答案
将 count
更改为 Ant.count
由于 count
是类成员(在Ant类的所有实例之间共享),并且不属于特定实例,因此应在类名的前缀下使用它.
As count
is a class member (shared between all instances of Ant class) and does not belong to a specific instance you should use it with the prefix of the class name.
class Ant:
count = 0
def __init__(self):
if Ant.count == 0:
self.real = True
else:
self.real = False
Ant.count += 1
这篇关于如何在__init__内更改类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文