gpt4 book ai didi

python:名称解析说明?

转载 作者:太空狗 更新时间:2023-10-30 02:51:27 25 4
gpt4 key购买 nike

我正在阅读 python 引用资料 name resolution ,上面写着

A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace.

基于此,我希望有以下代码

x = 10

def f():
x = 5

class Test:
y = x

return Test

print(f().y)

打印10,然而它打印5。这是引用中的错误,还是我误解了什么?

最佳答案

在这种情况下,“正常”规则适用:

x = 'global'

def f():
x = 'defined in f'

class Test:
print(x) # not local, normal rules apply

f()
# defined in f

在第二种情况下,如果我们在函数内部,我们会期望出现 UnboundLocalError: local variable 'x' referenced before assignment:

x = 'global'

def f():
x = 'defined in f'

class Test:
print(x) # unbound local at this time
x = 'assigned in Test'
print(x)

但是对于第一个print(x)x将从全局命名空间中获取:

f()
# global
# assigned in Test

关于python:名称解析说明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55830293/

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