这段Python代码是什么意思?

发布于 2024-09-27 19:18:20 字数 234 浏览 0 评论 0原文

__author__="Sergio.Tapia"
__date__ ="$18-10-2010 12:03:29 PM$"

if __name__ == "__main__":
    print("Hello")
    print(__author__)

它从哪里获得 __main____name__

感谢您的帮助

__author__="Sergio.Tapia"
__date__ ="$18-10-2010 12:03:29 PM$"

if __name__ == "__main__":
    print("Hello")
    print(__author__)

Where does it get __main__ and __name__?

Thanks for the help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

国粹 2024-10-04 19:18:20

__name__ 变量由运行时提供。它是当前模块的名称,即导入该模块时使用的名称。 "__main__" 是一个字符串。它并不特殊,只是一个字符串。它也恰好是执行主脚本时的名称。

if __name__ == "__main__": 机制是直接执行 .py 文件时执行某些操作的常用方法,但在将其作为模块导入时则不然。

The __name__ variable is made available by the runtime. It's the name of the current module, the name under which it was imported. "__main__" is a string. It's not special, it's just a string. It also happens to be the name of the main script when it is executed.

The if __name__ == "__main__": mechanism is the common way of doing something when a .py file is executed directly, but not when it is imported as a module.

暮光沉寂 2024-10-04 19:18:20

Python 模块也可以作为独立脚本运行。因此,只有当模块作为“主”文件执行时,if __name__ == "__main__": 块中的代码才会运行。

示例

#foo.py
def msg():
    print("bar")

if __name__ == "__main__":
    msg()

运行此模块将输出

$ python foo.py
bar

,而导入它则不会输出任何内容。

>>> import foo
>>> foo.msg()
bar

参考

Python modules can also be run as standalone scripts. As such, code within the if __name__ == "__main__": block will only run if the module is executed as the "main" file.

Example:

#foo.py
def msg():
    print("bar")

if __name__ == "__main__":
    msg()

Running this module will output

$ python foo.py
bar

where as importing it will output nothing.

>>> import foo
>>> foo.msg()
bar

Reference

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文