0

Hello Just curious on why the second instance already gets the category that was added in the first instance creation. How can i fix it?

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())


output


['kol', 'bol']
[]
['kol', 'bol', 'kol', 'bol']
[]
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    Create `self.category` in your `__init__` instead of using a class attribute (which is shared by the whole class) – khelwood Dec 17 '19 at 23:49

1 Answers1

1

To fix it declare category in __init__(), e.g.:

class Game_record:
    def __init__(self,name):
        self.name = name
        self.category = []

...

The reason why you observe that behavior is that if you declare category right after the class, it becomes a class-level attribute rather than an object-level attribute.

norok2
  • 25,683
  • 4
  • 73
  • 99