Python类中的全局变量和局部变量

2024-10-03 21:32:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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()
  1. 为什么x和y在这里不同?

  2. 如果我用函数范围替换class C,我将得到UnboundLocalError: local variable 'y' referenced before assignment,在这种情况下类和函数之间有什么区别?


Tags: of函数outputdefmayclassfuncprint
1条回答
网友
1楼 · 发布于 2024-10-03 21:32:10

这是因为class C的作用域实际上不同于def func的作用域,而且python具有不同的默认行为。你知道吗

下面是python寻找变量的基本方法

  • 查看当前范围
  • 如果当前作用域没有它->;使用最近的封闭作用域
  • 如果当前作用域有,但尚未定义->;使用全局作用域
  • 如果当前作用域有它,并且已经定义->;使用它
  • 否则就会爆炸

(如果你去掉ytop,你会得到一个NameError: name 'y' is not defined

所以基本上,当解释器看到下面的代码部分时

class C:
    print(x) # need x, current scope no x  -> default to nearest (xlocal)
    print(y) # need y, current scope yes y -> default to global (ytop)
             #         but not yet defined 
    y = 1
    print(y) # okay we have local now, switch from global to local

考虑以下场景

1) class C:
    print(x)
    print(y)

>>> xlocal
>>> ylocal

2) class C:
    y = 1
    print(x)
    print(y)  

>>> xlocal
>>> 1

3) class C:
    print(x)
    print(y)
    x = 1

>>> xtop
>>> ylocal

相关问题 更多 >