Say that I have the following Python code:
import sys
class DogStr:
tricks = ''
def add_trick(self, trick):
self.tricks = trick
class DogList:
tricks = []
def add_trick(self, trick):
self.tricks.append(trick)
# Dealing with DogStr
d = DogStr()
e = DogStr()
d.add_trick('trick d')
e.add_trick('trick e')
print(d.tricks)
print(e.tricks)
# Dealing with DogList
d = DogList()
e = DogList()
d.add_trick('trick d')
e.add_trick('trick e')
print(d.tricks)
print(e.tricks)
Running this code with Python 3.6.5, I get the following output:
trick d
trick e
['trick d', 'trick e']
['trick d', 'trick e']
The difference between DogStr and DogList is that I treat tricks
as a string on former and as a list on the latter.
When dealing with DogStr, tricks is behaving as an instance variable. BUT with DogList tricks is behaving as a class variable.
I was expecting to see the same behaviour on both calls, i.e.: if the two last lines of the output are identical, so should be the first two.
So I wonder. What is the explanation for that?