gpt4 book ai didi

python - 具有列表理解的类变量的范围

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

<分区>

看看下面的一段代码:

class a:
s = 'python'
b = ['p', 'y']
c = [x for x in s]

输出:

>>> a.c
['p', 'y', 't', 'h', 'o', 'n']

但是当我尝试使用 if 来限制列表时:

class a:
s = 'python'
b = ['p', 'y']
c = [x for x in s if x in b]

显示以下异常:

Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
class a:
File "<pyshell#22>", line 4, in a
c = [x for x in s if x in b]
File "<pyshell#22>", line 4, in <listcomp>
c = [x for x in s if x in b]
NameError: global name 'b' is not defined

如果 a make global b 有效,为什么会这样?

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