I am trying to understand something in Python.
When I have a property that I want shared across all subclasses, I place it in the parent class. I was expecting that the actual value of this property would be unique for each object instance. However, if this property is iterable and I modify it in one object, the change is made for all other instantiated objects.
class Animal:
sounds = []
def add_sounds(self, sound):
return self.sounds.append(sound)
class Cat(Animal):
pass
class Dog(Animal):
pass
cat = Cat()
cat.add_sounds('meow')
dog = Dog()
dog.add_sounds('bark')
print('The cat says: ' + str(cat.sounds))
print('The dog says: ' + str(dog.sounds))
This gives:
The cat says: ['meow', 'bark']
The dog says: ['meow', 'bark']
... but I was expecting:
The cat says: ['meow']
The dog says: ['bark']
This doesn't seem to be the case for other variable types like strings or numbers. What am I missing? This is Python 3.7.3.