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

Allen
  • 443
  • 2
  • 10
  • 20
  • Duplicate of all of these: http://stackoverflow.com/search?q=python+mutable+default+arguments. – S.Lott Sep 21 '11 at 15:31
  • possible duplicate of [Python: default value for a function](http://stackoverflow.com/questions/2313075/python-default-value-for-a-function) – S.Lott Sep 21 '11 at 15:32

3 Answers3

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."

wheaties
  • 35,646
  • 15
  • 94
  • 131
4

One possibility is:

class A:
    def __init__(self, n=None):
        if n is None:
            n = [0]
        self.data = n
NPE
  • 486,780
  • 108
  • 951
  • 1,012
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

eyquem
  • 26,771
  • 7
  • 38
  • 46