0
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?

1

3 Answers 3

7

You could try this:

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

Which avoids the biggest problem you're facing here, that is, that's the same list for every single object of your type "A."

Sign up to request clarification or add additional context in comments.

Comments

4

One possibility is:

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

Comments

0

Also:

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


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

print

b = A()
print b.data[0] #prints desired output  0

The principle is that it creates another list. If a long list is passed as argument, there will be two long list in memory. So the inconvenience is that it creates another list.... That's why I delete n.

Don't think it's better, but it may give you comprehension of what happens

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.