函数中没有Python代码的名称吗?

2024-03-29 05:00:11 发布

您现在位置:Python中文网/ 问答频道 /正文

标题差不多说明了这一点。你知道吗

我想知道我应该怎么称呼那些只存在于Python文件中而不存在于任何函数中的代码。你知道吗

对于某些上下文—在我所关注的特定模块中,有些函数具有已定义的定义,但在导入模块时,也会在末尾执行一些代码。这个代码叫什么?你知道吗


Tags: 模块文件函数代码标题定义末尾
2条回答

如果希望代码仅在直接执行时触发,请使用if __name__ == '__main__'条件:

__name__ is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own name, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported.

if __name__ == "__main__":
    # execute only if run as a script
    main()

此代码通常称为

global scope codemodule level codetop-level code

但是它没有合适的命名约定,但是当您使用其中任何一个时,程序员会理解您的意思。你知道吗

相关问题 更多 >