NameError in Python when listing static attributes from within same class

Viewed 136

I have the following 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("__")]

But it shows a NameError saying undefined variable 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?

4 Answers

In Python you cannot reference the class in the class body. The issue I see here is that you are referring to the class list_stuff within the class definition. 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.

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>]
Related