列出同一 class 中的静态属性时 Python 中的 NameError

NameError in Python when listing static attributes from within same class

我有以下 python class:

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

但是它显示一个 NameError 说未定义的变量 list_stuff

根据 ,它应该有效。

我也试过:

list_stuff().__dict__.items()

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

问题似乎是缩进,因为您实际上是从内部调用 class。

试试这个:

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

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

之外
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

我最终这样做了:

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

    @classmethod
    def stufflist(cls):
        return [v for k,v in cls.list_stuff.__dict__.items() if not k.startswith("__")]

和我的原意一样的效果

感谢大家的快速回复。

您可以创建一个方法来生成您想要的列表属性。首先,您需要在 运行 get_list() 方法之前生成 class 的实例。

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

def get_list(self):
    self.thelist = [v for k,v in list_stuff.__dict__.items() if not k.startswith("__")]
    return self.thelist

list_a = list_stuff()
print list_a.get_list()
print list_a.thelistenter code here

就是这样 returns:

['a', 'b', 'c', <function get_list at 0x7f07d6c63668>]
['a', 'b', 'c', <function get_list at 0x7f07d6c63668>]