python – 类范围中的闭包

前端之家收集整理的这篇文章主要介绍了python – 类范围中的闭包前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

根据我的理解,函数和类范围的行为几乎相同:

>>> def x():
...     a = 123
...     print (locals())
... 
>>> x()
{'a': 123}


>>> class x():
...     a = 123
...     print (locals())
... 
{'a': 123,'__module__': '__main__'}

但是,当我定义一个闭包时,行为是不同的.函数只是返回本地绑定,如预期的那样:

>>> def x():
...     a = 123
...     t = lambda: a
...     return t
... 
>>> x()()
123

而在一个类中,绑定似乎丢失了:

>>> class x():
...     a = 123
...     t = lambda self: a
... 
>>> x().t()
Traceback (most recent call last):
  File "

任何人都可以解释这种差异吗?

最佳答案
类范围是临时范围,它仅在执行类定义的主体时存在.生成的dict用于创建类命名空间,即类的__dict__.

就类中定义的函数而言,下一个范围“up”是类定义本身的范围.

以下工作正常:

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

这在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.

并在class compound statement documentation

The class’s suite is then executed in a new execution frame (see section 07002),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. 07003 A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary.

强调我的;执行帧是临时范围.

猜你在找的Python相关文章