Parent class init 正在继承期间执行
Parent class init is executing during inheritence
一道OOP基础题。
test.py
文件内容:
class test(object):
def __init__(self):
print 'INIT of test class'
obj = test()
然后我打开了另一个文件。
我刚刚继承了上面的测试class:
from test import test
class test1(test):
def __init__(self):
pass
所以当我 运行 这第二个文件时,来自父 class 的 __init__()
被执行(打印了 INIT)。
我读到我可以通过使用
来避免它
if __name__ == '__main__':
# ...
我可以克服这个问题,但我的问题是为什么父 class 的初始化正在执行,因为我只是在我的第二个文件中导入这个 class。为什么要执行对象创建代码?
导入模块会执行所有模块级语句,包括 obj=test()
。
为避免这种情况,仅在 运行 作为主程序时创建实例,而不是在导入时创建实例:
class test(object):
def __init__(self):
print 'INIT of test class'
if __name__ == '__main__':
obj=test()
问题不在于继承,而在于导入。在您的情况下,您在导入时执行 obj=test()
:
from test import test
当您导入 test
时,它的名称 __name__
是 test
。
但是当你 运行 你的程序在命令行上作为主程序时 python test.py
,它的名字是 __main__
。因此,在导入案例中,如果您使用:
,则跳过 obj=test()
if __name__ == '__main__':
obj=test()
一道OOP基础题。
test.py
文件内容:
class test(object):
def __init__(self):
print 'INIT of test class'
obj = test()
然后我打开了另一个文件。
我刚刚继承了上面的测试class:
from test import test
class test1(test):
def __init__(self):
pass
所以当我 运行 这第二个文件时,来自父 class 的 __init__()
被执行(打印了 INIT)。
我读到我可以通过使用
来避免它if __name__ == '__main__':
# ...
我可以克服这个问题,但我的问题是为什么父 class 的初始化正在执行,因为我只是在我的第二个文件中导入这个 class。为什么要执行对象创建代码?
导入模块会执行所有模块级语句,包括 obj=test()
。
为避免这种情况,仅在 运行 作为主程序时创建实例,而不是在导入时创建实例:
class test(object):
def __init__(self):
print 'INIT of test class'
if __name__ == '__main__':
obj=test()
问题不在于继承,而在于导入。在您的情况下,您在导入时执行 obj=test()
:
from test import test
当您导入 test
时,它的名称 __name__
是 test
。
但是当你 运行 你的程序在命令行上作为主程序时 python test.py
,它的名字是 __main__
。因此,在导入案例中,如果您使用:
obj=test()
if __name__ == '__main__':
obj=test()