0

With a optional argument in a function it is possible to access quantities of a different instance of a class. (see code below). Am I doing something wrong, or this this expected behavior?

Linux, Python 3.7.3 [GCC 7.3.0]

class Cat:
   def __init__(self, name):
       self.name = name
       print(name)

   def my(self,  d = {}):
       print('Before: ',d)
       d[self.name] = str(self.name)
       print('After: ',d)



tiger = Cat('Tiger')
tiger.my()


lion = Cat('Lion')
lion.my()

The code output is:

Tiger
Before:  {}
After:  {'Tiger': 'Tiger'}
Lion
Before:  {'Tiger': 'Tiger'}
After:  {'Tiger': 'Tiger', 'Lion': 'Lion'}
manifold
  • 1
  • 1
  • Possible duplicate of [Why does using \`arg=None\` fix Python's mutable default argument issue?](https://stackoverflow.com/questions/10676729/why-does-using-arg-none-fix-pythons-mutable-default-argument-issue) – snakecharmerb Oct 27 '19 at 19:00
  • See also https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument and https://docs.python.org/3/tutorial/controlflow.html#default-argument-values – snakecharmerb Oct 27 '19 at 19:00
  • 1
    Possible duplicate of ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – mkrieger1 Oct 27 '19 at 19:05
  • Does this answer your question? [How can I avoid issues caused by Python's early-bound default parameters (e.g. mutable default parameters "remembering" old data)?](https://stackoverflow.com/questions/366422/how-can-i-avoid-issues-caused-by-pythons-early-bound-default-parameters-e-g-m) – Karl Knechtel Mar 27 '23 at 06:53

0 Answers0