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?
__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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.