0

I'm currently learning Python in OOP, I have a question about using list as a class attribute. The question is when I change something in objects it will also change that class attribute.

class Backet:
   number_of_stone = 0
   stone_collection = []
   
   def __init__(self,name):
      self.name = name
      self.number_of_stone +=1
      self.stone_collection.append(self.name)

stone_one = Backet('One')
stone_two = Backet('Two')

When I print out the stone_one and stone_two.number_of_two they are = 1 (I know this is correct). But when I print stone_one and stone_two.stone_collection they both give a list ["One","Two"].

My question is that should it be stone_one.stone_collection = ['One'] and stone_two.stone_collection = ['Two']

John Ho
  • 13
  • 3
  • 1
    Class attribute like `stone_collection` is the same for all instances of the class and since it's also mutable (list), each instance will change the core object which will affect all other instances. – NotAName Aug 26 '21 at 06:29
  • ```stone_collection``` is a class variable. A class variable is defined inside the class but no inside any method. A class variable is shared for all instances of the class –  Aug 26 '21 at 06:29
  • Why are you making `number_of_stone = 0` anf `stone_collection = []` class variables? – juanpa.arrivillaga Aug 26 '21 at 06:35

1 Answers1

1

Change stone_collection to instance variable:

class Backet:
   def __init__(self, name):
      number_of_stone = 0
      stone_collection = []
      self.name = name
      self.number_of_stone +=1
      self.stone_collection.append(self.name)

stone_one = Backet('One')
stone_two = Backet('Two')