3

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?

snake_charmer
  • 2,845
  • 4
  • 26
  • 39
EricBlair1984
  • 339
  • 4
  • 16

4 Answers4

1

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

Cyzanfar
  • 6,997
  • 9
  • 43
  • 81
  • That works. But I wanted to keep it inside the class, so i ended up using a @classmethod, then referenced the classname with cls.list_stuff. This gives me the same effect I wanted originally. – EricBlair1984 Nov 03 '17 at 19:22
  • That’s true you could do it achieve what you want that way! Happy to help :) – Cyzanfar Nov 03 '17 at 19:24
1

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.

EricBlair1984
  • 339
  • 4
  • 16
0

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("__")]
leiberl
  • 73
  • 1
  • 5
0

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>]
snake_charmer
  • 2,845
  • 4
  • 26
  • 39