gpt4 book ai didi

python - 列出同一类中的静态属性时 Python 中的 NameError

转载 作者:行者123 更新时间:2023-11-28 17:11:49 25 4
gpt4 key购买 nike

我有以下 python 类:

class list_stuff:    
A = 'a'
B = 'b'
C = 'c'
stufflist = [v for k,v in list_stuff.__dict__.items() if not k.startswith("__")]

但是它显示了一个 NameError 说 undefined variable list_stuff

根据 this ,它应该可以工作。

我也尝试过:

list_stuff().__dict__.items()

但还是一样的错误。我在这里缺少什么?

最佳答案

在 Python 中,您不能在类主体中引用类。我在这里看到的问题是您指的是类定义中的类 list_stuff。要解决这个问题,只需将该行移到类之外:

class list_stuff:    
A = 'a'
B = 'b'
C = 'c'

stufflist = [v for k,v in list_stuff.__dict__.items() if not k.startswith("__")]

这是 documentation on classes

关于python - 列出同一类中的静态属性时 Python 中的 NameError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47102764/

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