if __name__ =='__ main__'不工作ipython [英] if __name__ == '__main__' not working ipython
问题描述
我无法获取如果__name =='__ main __'
技巧在IPython,Spyder环境中工作。我尝试过这个帖子中给出的每一种方法:
if __name__ =='__ main__'在IPython中
I'm having trouble getting the if __name == '__main__'
trick to work in an IPython, Spyder environment. I've tried every approach given in this thread:
if __name__ == '__main__' in IPython
这是我的超级简化模块
Module1.py
Module1.py
Class UnitTest():
print 'Mod1 UnitTest!'
if __name__ == '__main__':
UnitTest()
Module2.py
Module2.py
import Module1
Class UnitTest():
print 'Mod2 UnitTest!'
if __name__ == '__main__':
UnitTest()
所以我运行Module2.py而且我总是看到 Mod2 UnitTest
和 Mod1 UnitTest
已打印。这些是在IPython内核中执行的。我只想显示 Mod2 UnitTest
消息。
So I run Module2.py and I always am seeing both Mod2 UnitTest
and Mod1 UnitTest
printed. These are executing in an IPython kernel. I want only the Mod2 UnitTest
message to display.
知道怎么回事?
推荐答案
我之前因为尴尬而删除了这个问题,但是如果其他任何新手都看到这个问题,也可以分享。
Well I deleted this question earlier out of embarrassment but might as well share in case any other newb sees this.
我忘记将UnitTest行放在 __ init __
方法中。因此,在定义类时每次运行单元测试,而不是在实例化对象时运行。代码应为:
I forgot to put the UnitTest line inside of the __init__
method. So the unit test was being run every single time when the class was defined and not when the object was instantiated. The code should be:
Module1.py
Module1.py
Class UnitTest():
def __init__(self):
print 'Mod1 UnitTest!'
if __name__ == '__main__':
UnitTest()
Module2.py
Module2.py
import Module1
Class UnitTest():
def __init__(self):
print 'Mod1 UnitTest!'
if __name__ == '__main__':
print 'Mod2 UnitTest!'
这篇关于if __name__ =='__ main__'不工作ipython的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!