循环Python类中的对象实例
你好,我只是好奇为什么第二个实例已经得到了第一个实例创建中添加的类别。我怎样才能修好它循环Python类中的对象实例,python,python-3.x,list,class,Python,Python 3.x,List,Class,你好,我只是好奇为什么第二个实例已经得到了第一个实例创建中添加的类别。我怎样才能修好它 class Game_record: category = [] def __init__(self,name): self.name = name def add_category(self, cat): self.category.append(cat) def reset_cat(self): self.category = []
class Game_record:
category = []
def __init__(self,name):
self.name = name
def add_category(self, cat):
self.category.append(cat)
def reset_cat(self):
self.category = []
def ret_cat(self):
return self.category
game = ["a","b"]
for each in game:
g = Game_record( each )
g.add_category("kol")
g.add_category("bol")
print(g.ret_cat())
g.reset_cat()
print(g.ret_cat())
输出
['kol', 'bol']
[]
['kol', 'bol', 'kol', 'bol']
[]
要修复它,请在
\uuuu init\uuuu()
中声明类别
,例如:
class Game_record:
def __init__(self,name):
self.name = name
self.category = []
...
您观察该行为的原因是,如果您在类之后立即声明
category
,它将成为类级属性而不是对象级属性。在\uuuu init\uuu
中创建self.category
,而不是使用class属性(由整个类共享)