0

When I run this code, I expected all 4 scenarios to produce the same answer, yet scenario 4 produces a different one, please help me undertand why this is, or is it a bug?

class myclass():
def __init__(self, test=[]):
    self.test = test
def mymethod(self, content):
    self.test = self.test + [content]
def myothermethod(self, content):
    self.test.append(content)

print('scenario 1')
x = myclass()
print('x: ', x)
print('x.test: ', x.test)
x.mymethod(123)
print('x.test: ', x.test)

print('scenario 2')
x = myclass()
print('x: ', x)
print('x.test: ', x.test)
x.mymethod(123)
print('x.test: ', x.test)

print('scenario 3')
y = myclass()
print('y: ', y)
print('y.test: ', y.test)
y.myothermethod(123)
print('y.test: ', y.test)

print('scenario 4')
y = myclass()
print('y: ', y)
print('y.test: ', y.test)
y.myothermethod(123)
print('y.test: ', y.test)

And the output is:

scenario 1
x:  <__main__.myclass object at 0x7f904c2fa940>
x.test:  []
x.test:  [123]
scenario 2
x:  <__main__.myclass object at 0x7f904c2fa160>
x.test:  []
x.test:  [123]
scenario 3
y:  <__main__.myclass object at 0x7f904c2fa940>
y.test:  []
y.test:  [123]
scenario 4
y:  <__main__.myclass object at 0x7f904c2fa190>
y.test:  [123]
y.test:  [123, 123]

I understand that .append only appends the reference, but in scenario 4 when the entire class is newly reinstantiated, why does is it already include 123 in the .test variable list, rather than the class's default of an empty list?

0 Answers0