x = "xtop"
y = "ytop"
def func():
x = "xlocal"
y = "ylocal"
class C:
print x #xlocal of course
print y #ytop why? I guess output may be 'ylocal' or '1'
y = 1
print y #1 of course
func()
为什么x和y在这里不同?
如果我用函数范围替换class C
,我将得到UnboundLocalError: local variable 'y' referenced before assignment
,在这种情况下类和函数之间有什么区别?
这是因为
class C
的作用域实际上不同于def func
的作用域,而且python具有不同的默认行为。你知道吗下面是python寻找变量的基本方法
(如果你去掉
ytop
,你会得到一个NameError: name 'y' is not defined
)所以基本上,当解释器看到下面的代码部分时
考虑以下场景
相关问题 更多 >
编程相关推荐