ami*_*mit 4 python import module
我需要使用python模块(在某些库中可用).该模块如下所示:
class A:
def f1():
...
print "Done"
...
Run Code Online (Sandbox Code Playgroud)
我只需要A类的功能.但是,当我导入模块时,底部的代码(print和其他)会被执行.有没有办法避免这种情况?基本上我需要导入一个模块的一部分:"来自module1 import A",它应该只导入A.是否可能?
unw*_*ind 11
是的,当然:
from module1 import A
Run Code Online (Sandbox Code Playgroud)
是一般语法.例如:
from datetime import timedelta
Run Code Online (Sandbox Code Playgroud)
应该保护底部的代码在导入时运行,方法如下:
if __name__ == "__main__":
# Put code that should only run when the module
# is used as a stand-alone program, here.
# It will not run when the module is imported.
Run Code Online (Sandbox Code Playgroud)