python中关于if name == 'main'

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lql0716/article/details/77342816

python中关于if name == ‘main’

author@jason_ql(lql0716)
http://blog.csdn.net/lql0716


  • __name__ 是当前模块名,当模块被直接运行时模块名为 __main__。这句话的意思就是,当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行。

  • 示例

# file one.py
def func():
    print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported into another module")

# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

如果你执行one.py文件
python one.py
会输出:

top-level in one.py
one.py is being run directly

如果你执行two.py文件,
python two.py
会输出:

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly

猜你喜欢

转载自blog.csdn.net/lql0716/article/details/77342816