0

This is surprising me a bit, as I had expected that the default lst attribute in the instances of the class below are fresh list objects, and not the same one! I know if I move the initialization of the attribute to the body of the init this problem seems to be solved, but I still would like to understand what the point behind this design decision has been, since I am learning Python3.



class C:
   def __init__(self, lst=list()):
       self.lst = lst
       
c1=C()
c2=C()
c3=C()

print(id(c1.lst) == id(c2.lst) == id(c3.lst))

The above code returns (to my astonishment!) True.

Student
  • 708
  • 4
  • 11
  • 2
    Default values are evaluated when the function is defined, not every time the function is called. – Barmar Mar 11 '21 at 22:12
  • 1
    This is not specific to class methods, it's the same as ordinary functions. – Barmar Mar 11 '21 at 22:13
  • There's probably no great answer other than "this was a straight-forward way of implementing default parameters when they were added to the language. It turns out,this was very counter-intuitive to most users, but it's how it works now and how it has worked for a long time, so we aren't going to change it" – juanpa.arrivillaga Mar 11 '21 at 22:53

0 Answers0