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']
tricksis a class instance so there is only one copy shared by every instance ofPartyAnimal().C++your variablesx,nameandtrickswould bestatici.e. there are shared by all instances of your class. To make them specific to an instance of your class, assign them toselfonly.self.tricks.append(trick)modifies the existingtricksclass attribute, butself.x += 1does not modify thexclass attribute because you're performing an assignment. Instead, it creates anxinstance attribute (which shadows the class attribute of the same name) to hold the new integer object.self.tricks = self.tricks + [trick]that would also create atricksinstance attribute, although using+=wouldn't, it'd just mutate the class attribute, like the.appendmethod does.+=on an integer can't mutate the integer because Python integers are immutable.