if __name__ == ‘__main__’ 如何正确理解?

2020年9月23日17:53:37 发表评论 30 views
# 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

Thus, when module one gets loaded, its __name__ equals "one" instead of __main__.我就不翻译了首先我翻译的很丑其次我觉得英文更好理解。。。它就是上面这么用的。然后我觉得它的功能就是,让if __name__ == '__main__'它后面的代码不执行。这样代码运行会更简洁更流畅???因为只需要用想用的那部分就行了。。。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: