0

I have a simple python class where I am initializing an instance variable. I am expecting that when I initialize two different objects of that class, each time the instance variable will be initialized afresh. But that is not the case I see in my notebook output. The initialization output of b is as if the object from the initialization of a is held onto.

class MyQueue(object):

    def __init__(self,stackA=[]):
        print(stackA)
        self.stackA = stackA
        stackA.append('x')
        print('inside init ',stackA)

    def addElement(self, elem):
        print('before append ',self.stackA)
        self.stackA.append(elem)
        print('after append ',self.stackA)
a = MyQueue()
b = MyQueue()
a==b

I expect

[]
inside init  ['x']
[]
inside init  ['x']
False

But get,

[]
inside init  ['x']
['x']
inside init  ['x', 'x']
False
khelwood
  • 55,782
  • 14
  • 81
  • 108
Tito Mitra
  • 11
  • 2
  • The problem is with the default empty list in `__init__`. Change that to a `None` and handle the condition within the function. That'll solve your issue – inspectorG4dget Jul 24 '19 at 21:14
  • 1
    I wouldn't worry too much that your question was marked as a duplicate. I think that this was a well-formulated question with relevant code and expected/actual output, and the "Least Astonishment" post that was linked would be hard to find if you are a beginner. – Samantha Jul 24 '19 at 21:22

1 Answers1

3

The problem is the mutable default argument in your constructor. inspectorG4dget's comment is correct in that you are experiencing the same problem as the linked post describes.

You can achieve your desired behavior by making the following change:

def __init__(self,stackA=None):
    if stackA is None:
        stackA = []
    print(stackA)
    self.stackA = stackA
    stackA.append('x')
    print('inside init ',stackA)
Samantha
  • 275
  • 1
  • 12