gpt4 book ai didi

Python 3 - 类变量未定义

转载 作者:太空狗 更新时间:2023-10-29 21:06:33 25 4
gpt4 key购买 nike

<分区>

这里我无法访问 Python 中的类变量列表理解

class Student:
max_year = 18
year_choice = [i for i in range(100) if i > max_year]

def __init__(self, name):
self.name = name
print (self.year_choice)

Student('Blah')

但它在 Python 2 中运行良好。

../workspace$ python student.py
[19, 20, 21, 22, 2.... 99]

但是在 Python 3 中出现错误。

../workspace$ python student.py
File "student.py", line 18, in <listcomp>
year_choice = [i for i in range(100) if i > max_year]
NameError: name 'max_year' is not defined

从调试这个当我改变的时候以下声明

[i for i in range(100) if i > max_year]

对此

[i for i in range(max_year)] # don't look too much into it ;)

工作正常。为什么我无法访问 if/else list comprehension 中的类变量?

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