【发布时间】:2019-07-13 05:44:26
【问题描述】:
考虑这段代码:
def gee(bool_, int32, int64, str_):
class S:
bool_ = bool_
int32 = int32
int64 = int64
str_ = str_
return S
gee(1, 2, 3, 4)
运行会报错:
Traceback (most recent call last):
File "test_.py", line 36, in <module>
gee(1, 2, 3, 4)
File "test_.py", line 27, in gee
class S:
File "test_.py", line 28, in S
bool_ = bool_
NameError: name 'bool_' is not defined
我不知道这里适用哪些范围/关闭规则。 nonlocal 修复了错误但结果不是我所期望的:
def gee(bool_, int32, int64, str_):
class S:
nonlocal bool_, int32, int64, str_
bool_ = None
int32 = None
int64 = None
str_ = None
print(bool_, int32, int64, str_ )
return S
g = gee(1, 2, 3, 4)
g.bool_
输出:
None None None None
Traceback (most recent call last):
File "test_.py", line 38, in <module>
g.bool_
AttributeError: type object 'S' has no attribute 'bool_'
除了重命名之外,我还能做些什么来使第一个代码 sn-p 中的分配工作?为什么它会这样?因为有name = ...?为什么 Python 在赋值之前不评估名称?
【问题讨论】:
标签: python scope closures inner-classes