根据我的理解,函数和类范围的行为几乎相同:
>>> 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 "
任何人都可以解释这种差异吗?
就类中定义的函数而言,下一个范围“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.
强调我的;执行帧是临时范围.