Search code examples
pythonclassobjectmutable

Python, mutable object as default argument, is there any way to solve?


class A:
    def __init__(self, n=[0]):
        self.data = n

a = A()
print a.data[0] #print 0
a.data[0] +=1

b = A()
print a.data[0] #print 1, desired output is 0

In the case above, is there any way to provide a default argument with the mutable object (such as list or class) in __init__() class A, but b is not affected by the operation a?


Solution

  • One possibility is:

    class A:
        def __init__(self, n=None):
            if n is None:
                n = [0]
            self.data = n