I just started learning Python and come from a Java/C++ background and find the following behavior a little confusing. After calling s.add_trick("Woof") and d.add_trick("Woof"), s.tricks and d.tricks both contain ["Woof", "Bark"]. However, calling party() doesn't have the same behavior. Can someone explain?
class PartyAnimal:
x = 0
name = ''
tricks = []
def __init__(self, name):
self.name = name
def party(self):
self.x += 1
def add_trick(self, trick):
self.tricks.append(trick)
s = PartyAnimal("Sally")
d = PartyAnimal("Danny")
s.party()
d.party()
s.add_trick("Woof")
d.add_trick("Bark")
print 's', s.name, s.x, s.tricks
print 'd', d.name, d.x, d.tricks
Output is this:
s Sally 1 ['Woof', 'Bark']
d Danny 1 ['Woof', 'Bark']