什么是Python中的顶级语句?

时间:2013-08-08 23:54:29

标签: python

在Python指南的project structure一章中,术语“顶级语句”被提出了几次。我不确定这到底是什么意思。我的猜测是,任何变量声明都发生在加载模块后立即触发的任何函数或类方法之外。它是否正确?它是否还包含模块的import语句?

4 个答案:

答案 0 :(得分:19)

这不仅仅是变量声明(并且无论如何都没有变量声明)。这几乎是从缩进级别0开始的任何事情。

import sys         # top-level

3 + 4              # top-level

x = 0              # top-level

def f():           # top-level
    import os      # not top-level!
    return 3       # not top-level

if x:              # top-level
    print 3        # not top-level
else:
    print 4        # not top-level, but executes as part of an if statement
                   # that is top-level

class TopLevel(object): # top-level
    x = 3          # not top-level, but executes as part of the class statement
    def foo(self): # not top-level, but executes as part of the class statement
        print 5    # not top-level

答案 1 :(得分:2)

我认为你完全正确,是的,那将包括import语句。

答案 2 :(得分:2)

这是第一次提到“顶级声明”:

  

找到modu.py后,Python解释器将在隔离的范围内执行该模块。将执行modu.py中的任何顶级语句,包括其他导入(如果有)。函数和类定义存储在模块的字典中。

这清楚地表明他们真正的意思是“在import时间解释的事物。”

虽然它不直接有用,但Python documentation itself也使用短语“top-level”(组件,在此上下文中表示“语句”)。

请注意此模块:

"""a python module, spam.py"""

def spam():
    return "spam"

class Spam(object):
    pass

中有两个语句,defclass。这些都是在导入时执行。这些定义是复合语句(请参阅defclass描述)。如果将装饰器附加到顶级def,则会添加更多顶级的东西来运行。 (另请参阅user2357112's answer:运行class语句会调用更多内部工作。)

在顶部添加import sys,您添加了第三个语句,即导入sys。但是,如果你添加这个:

def ham(eggs):
    import os
    return os.path.basename(eggs)

您仍然只在顶级内容中添加了一条语句def ham。当ham本身被执行(调用)时,import os将被运行。

答案 3 :(得分:0)

在python中,未缩进的语句称为顶层语句。 python在内部为顶级语句s赋予特殊名称,即__main__

相关问题