简体   繁体   English

在同一个类中列出静态属性时,Python中的NameError

[英]NameError in Python when listing static attributes from within same class

I have the following python class: 我有以下python类:

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

But it shows a NameError saying undefined variable list_stuff . 但是它显示了一个NameError,表示未定义的变量list_stuff

According to this , it should work. 根据这个 ,它应该工作。

I also tried with: 我也尝试过:

list_stuff().__dict__.items()

But still same error. 但仍然是同样的错误。 What am I missing here? 我在这里错过了什么?

In Python you cannot reference the class in the class body. 在Python中,您无法在类体中引用该类。 The issue I see here is that you are referring to the class list_stuff within the class definition. 我在这里看到的问题是你指的是类定义中的class list_stuff To resolve simply move that line outside the class: 要解决只是在课外移动该行:

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

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

Here is the documentation on classes 这是关于类文档

I ended up doing this: 我最终这样做了:

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("__")]

which has the same effect as my original intent. 这与我原来的意图具有相同的效果。

Thanks all for quick replies. 谢谢大家的快速回复。

The problem seems to be the indentation, as you are essentially calling the class from within. 问题似乎是缩进,因为你实际上是从内部调用类。

Try this: 尝试这个:

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

You can create a method that would generate the list attribute you wish. 您可以创建一个生成所需列表属性的方法。 First you will need to generate an instance of that class, before running the get_list() method. 首先,在运行get_list()方法之前,您需要生成该类的实例。

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

This is what it returns: 这是它返回的内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM