2

In the example below, we see C1.__init__() has been executed before either of the class objects have been instantiated. Is there any way to avoid this?

Python 3.7.5 (default, Nov  7 2019, 10:50:52) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class C1:
...     def __init__(self):
...        print('C1.__init__ executed')
... 
>>> class C2:
...     def meth_C2(self, c1=C1()):
...         print('C2.__init__ executed')
... 
C1.__init__ executed
user2309803
  • 541
  • 5
  • 15
  • 2
    Yes, an object is instantiate here: `def meth_C2(self, c1=C1())`. And no, you can't avoid that. Generally, you set it to `None` and then use `if c1 is None: c1 = C1()` – juanpa.arrivillaga May 10 '20 at 18:53
  • 1
    `def meth_C2(self, c1=None):if c1 is None:c1=C1() ...` – azro May 10 '20 at 18:55
  • @juanpa.arrivillaga @azro Thanks for your answers. That implies the caller of a class method must supply `None` for every default helper class (such as `C1()`) 'passed in'. That's a shame – user2309803 May 10 '20 at 19:21
  • @user2309803 no, you just make the default value `None` or any appropriate sentinel, so the caller doesn't need to worry about it.. See the linked duplicate – juanpa.arrivillaga May 10 '20 at 19:24
  • @juanpa.arrivillaga you are right, I forgot to instantiate `C2` before calling `meth_C2`, thanks again – user2309803 May 10 '20 at 19:34

0 Answers0