1

I cannot figure out why the local variable lst is [1] when called the second time where no arguments are passed to the __init__ method. I expected it to be overridden by the default value, [].

import sys
print(sys.version)
    
class A():
    def __init__(self, elem=None, lst=[]):
        if elem:
            lst.append(elem)
        print(lst)


A(1)
A()

The output is

3.8.2 | packaged by conda-forge | (default, Mar  5 2020, 17:29:01) [MSC v.1916 64 bit (AMD64)]
[1]
[1]
Mads M Pedersen
  • 579
  • 6
  • 16

1 Answers1

4

Here is very helpful links for this

In short, Python’s default arguments are evaluated once when the function is defined

Joona Yoon
  • 314
  • 3
  • 16