nkr*_*rkv 4 python nested class
以下工作正常,即它没有给出任何错误:
def foo(arg):
class Nested(object):
x = arg
foo('hello')
Run Code Online (Sandbox Code Playgroud)
但以下引发异常:
def foo(arg):
class Nested(object):
arg = arg # note that names are the same
foo('hello')
Run Code Online (Sandbox Code Playgroud)
追溯:
Traceback (most recent call last):
File "test.py", line 6, in <module>
foo('hello')
File "test.py", line 3, in foo
class Nested(object):
File "test.py", line 4, in Nested
arg = arg
NameError: name 'arg' is not defined
Run Code Online (Sandbox Code Playgroud)
我无法理解这种行为的原因.有人可以解释一下吗?
该arg属性隐藏了arg函数参数(内部范围)
def foo(arg):
class Nested(object):
arg = arg # you try to read the `arg` property which isn't initialized
Run Code Online (Sandbox Code Playgroud)
如果i = i在没有初始化i变量的情况下键入解释器窗口,则会出现相同的错误 .