gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:38 25 4
gpt4 key购买 nike

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,类和类有什么区别以及这种情况下的功能?

最佳答案

这是因为 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 scope

考虑以下场景以及我们在每种情况下会得到的不同输出

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

关于python - Python 类中的全局变量和局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48247674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com