[英]parent class init is executing during inheritence
One basic question in OOP. OOP中的一个基本问题。
test.py
file content: test.py
文件内容:
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? 我可以克服这个问题,但是我的问题是为什么父类的init正在执行,因为我只在第二个文件中导入该类,所以对象创建代码如何执行?
Importing a module executes all module-level statements, including obj=test()
. 导入模块将执行所有模块级别的语句,包括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: 在您的情况下,您在导入时执行obj=test()
:
from test import test
When you import test
, its name __name__
is test
. 导入test
,其名称__name__
为test
。 But when you run your program on the command line as main program with python test.py
, its name is __main__
. 但是,当您使用python test.py
在命令行上将程序作为主程序运行时,其名称为__main__
。 So, in the import case, you skip obj=test()
if you use: 因此,在导入情况下,如果使用,则跳过obj=test()
:
if __name__ == '__main__':
obj=test()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.