I\'m still fairly new to Python, and my OO experience comes from Java. So I have some code I\'ve written in Python that\'s acting very unusual to me, given the following code:<
I believe the difference is that +=
is an assignment (just the same as =
and +
), while append
changes an object in-place.
mylist = []
mynum = 0
This assigns some class variables, once, at class definition time.
self.mylist.append("Hey!")
This changes the value MyClass.mylist
by appending a string.
self.mynum += 1
This is the same as self.mynum = self.mynum + 1
, i.e., it assigns self.mynum
(instance member). Reading from self.mynum
falls through to the class member since at that time there is no instance member by that name.