加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 类范围中的闭包

发布时间:2020-12-16 21:59:13 所属栏目:Python 来源:网络整理
导读:根据我的理解,函数和类范围的行为几乎相同: def x():... a = 123... print (locals())... x(){'a': 123} class x():... a = 123... print (locals())... {'a': 123,'__module__': '__main__'} 但是,当我定义一个闭包时,行为是不同的.函数只是返回本地绑定,

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读