Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
循环Python类中的对象实例_Python_Python 3.x_List_Class - Fatal编程技术网

循环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属性(由整个类共享)