One basic question in OOP.
test.py
file content:
class test(object):
def __init__(self):
print 'INIT of test class'
obj=test()
Then I opened another file.
I just inherited from the above test class:
from test import test
class test1(test):
def __init__(self):
pass
So when I run this class, the init from parent class is executing.
I read that I can avoid it by using
if __name__='__main__'
I can over come this, but my question is why the parent class's init is executing as I am just importing this class only in my second file, how the object creation code executed?
Importing a module executes all module-level statements, including obj=test()
. To avoid this, make an instance only when run as the main program, not when imported:
class test(object):
def __init__(self):
print 'INIT of test class'
if __name__ == '__main__':
obj=test()
The problem is not the inheritance but the import. In your case you execute obj=test()
when importing:
from test import test
When you import test
, its name __name__
is test
. But when you run your program on the command line as main program with python test.py
, its name is __main__
. So, in the import case, you skip obj=test()
if you use:
if __name__ == '__main__':
obj=test()
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.