-1

I have a main class creating an instance of another class, which has to be imported first. After debugging a while I found out, that the code within the __init__ method of the imported class runs when I import it. However, for my code to properly work I need it to not be run when imported. I already found this thread, but it doesn't really help me. For testing I wrote a simple application where the problem doesn't appear:

test.py:

class foo:
    def __init__(self):
        print("foo")

main.py:

from test import foo
def main():
    print("bar")
    t = foo()

The code works as expected, the out put is first "bar", then "foo".

When is the __init__ code executed and when not?

khelwood
  • 55,782
  • 14
  • 81
  • 108
tcq
  • 11
  • 2
  • The `__init__` method of your class is executed when the class is instantiated. It is typically not executed when your class is not instantiated. I'm not sure how we're supposed to diagnose your problem from code that works as expected. – khelwood Sep 02 '20 at 12:17
  • I can't share the code where it is not working as expected since it is not mine. I basically import a class and it seems like the __init__ code of the imported class is run during the importation – tcq Sep 02 '20 at 12:28
  • You don't have to share the original code, but you should make a [mre] that actually reproduces the problem if you want an explanation. – khelwood Sep 02 '20 at 12:32
  • They are probably instantiating an instance of that class in the package you are importing and thus it's `__init__` method is being run. Remeber that you import a package nor a class so the package may have more things (like instantiating a class). In other words, they probably have `t = foo()` inside `test.py` and when you do `from test import foo` you are executing that code not only importing the class. – Adirio Sep 02 '20 at 12:37

1 Answers1

2

__init__() of your foo class is executed when you call foo()

So in your case the constructor call will occure when you do t = foo()

Xeyes
  • 583
  • 5
  • 25