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?

4
  • 1
    Try this: stackoverflow.com/questions/9058305/… Commented Nov 3, 2017 at 19:02
  • seems difficult from the inside. Commented Nov 3, 2017 at 19:03
  • Nonsense. Undefined variables aren't syntax errors. Commented Nov 3, 2017 at 19:17
  • it's a NameError Commented Nov 3, 2017 at 19:20

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
That’s true you could do it achieve what you want that way! Happy to help :)
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.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.