Defining constants in python class, is self really needed?

Theodor picture Theodor · Oct 22, 2010 · Viewed 49.8k times · Source

I want to define a set of constants in a class like:

class Foo(object):
   (NONEXISTING,VAGUE,CONFIRMED) = (0,1,2)
   def __init__(self):
       self.status = VAGUE

However, I get

NameError: global name 'VAGUE' is not defined

Is there a way of defining these constants to be visiable inside the class without resorting to global or self.NONEXISTING = 0 etc.?

Answer

Thomas Wouters picture Thomas Wouters · Oct 22, 2010

When you assign to names in the class body, you're creating attributes of the class. You can't refer to them without referring to the class either directly or indirectly. You can use Foo.VAGUE as the other answers say, or you can use self.VAGUE. You do not have to assign to attributes of self.

Usually, using self.VAGUE is what you want because it allows subclasses to redefine the attribute without having to reimplement all the methods that use them -- not that that seems like a sensible thing to do in this particular example, but who knows.