I have been doing inheritance recently, and I am a little confused by the behavior of the following:
class Foo(list):
def method(self, thing):
new = self + [thing]
print(new)
self = new
print(self)
def method2(self, thing):
self += [thing]
>>> f = Foo([1, 2, 3, 4, 5])
>>> f.method(10)
[1, 2, 3, 4, 5, 10]
[1, 2, 3, 4, 5, 10]
>>> f
[1, 2, 3, 4, 5]
>>> f.method2(10)
>>> f
[1, 2, 3, 4, 5, 10]
Why method2does the in-place method work, but the first does not work?
source
share