首页 > 代码库 > Pythonz中模块内的__name__用法示例

Pythonz中模块内的__name__用法示例

作者:知乎用户
链接:https://www.zhihu.com/question/49136398/answer/114437881
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

貌似昨天还是前天看过这个~现学现卖一下,有错误的话大家走过路过请指正一下~谢谢!
我的理解是,呜呜为什么我感觉我可以理解但是说不出来。。。我是看下面这段代码懂了的,引用自python - What does if __name__ == "__main__" do?其中Adam Rosenfield的回答。
# 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__‘它后面的代码不执行。这样代码运行会更简洁更流畅???因为只需要用想用的那部分就行了。。。

Pythonz中模块内的__name__用法示例