-1

The class definition:

class tr():
  def __init__(self,l=[]):
    self.l = l
  def added(self):
    self.l.append(1)
colt1 = tr()
colt1.added()
print(colt1.l)

Output is [1] Executed the below code after the above one

colt2 = tr()
colt2.added()
print(colt2.l)

Output is [1, 1]

I would like to have the output for the second segment also to be [1] with the class getting the data members from the init function and also having a default argument. So how should I alter the code to get this output?

Vikram
  • 110
  • 6
  • 1
    See also https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – Dennis Apr 25 '22 at 05:05
  • Oh! This page has answered the question, But I was unable to locate it, Should be because of the fancy title!! – Vikram Apr 25 '22 at 05:09

1 Answers1

1

The standard thing to do is have this sort of thing for your __init__ method:

    def __init__(self, l=None):
        if l is None:
            l = []
        self.l = l

You can check out this FAQ entry: https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects

Dennis
  • 2,249
  • 6
  • 12