且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在类作用域中关闭

更新时间:2023-02-26 19:50:53

类范围是一个临时范围,它只在执行类定义的主体时存在。生成的 dict 用于创建类命名空间,类的 __ dict __

The class scope is a temporary scope, it only exists while executing the body of the class definition. The resulting dict is used to create the class namespace, the __dict__ of the class.

对于类中定义的函数,下一个范围'up'是 class 定义本身的范围。

As far as functions defined in a class are concerned, the next scope 'up' is the scope of the class definition itself.

以下工作正常:

>>> def foo():
...     spam = 'eggs'
...     class Bar(object):
...         def baz(self): return spam
...     return Bar()
... 
>>> foo().baz()
'eggs'

=http://www.python.org/dev/peps/pep-0227/ =nofollow> pep 227 :

This is documented in pep 227:


无法访问类作用域中的名称。名称在
中解析为最内层函数作用域。如果类定义
出现在嵌套作用域链中,则解析过程跳过
类定义。

Names in class scope are not accessible. Names are resolved in the innermost enclosing function scope. If a class definition occurs in a chain of nested scopes, the resolution process skips class definitions.

复合语句文档

and in the class compound statement documentation:


然后,该类的套件在一个新的执行框架中执行(参见 命名和绑定 ),使用新创建的本地命名空间和原始全局命名空间。 (通常,套件只包含函数定义。)当类的套件完成执行时,其执行框架被丢弃,但其本地命名空间已保存 [4] 然后使用继承列表创建类对象基本类和保存的属性字典的本地命名空间。

The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. [4] A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary.

强调我;执行框架是临时范围。

Emphasis mine; the execution frame is the temporary scope.