views:

66

answers:

3

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.?

+3  A: 

try instead of:

self.status = VAGUE

this one:

self.status = Foo.VAGUE

you MUST specify the class

Matus
A: 

The only way is to access it through the class name such as

Foo.VAGUE

If accessing just VAGUE inside the __init__ function, or a function, it must be declared inside that to access it the way you want.

Using self is for the instance of the class also.

Iacks
ok, thats too bad. I recall that you could do something like what I was trying to do in java? I'm not sure.
Theodor
I am pretty sure you can do just what you asked in Java!
Iacks
And I'm pretty sure that you cant do 90% of the other stuff you want to do in java.
aaronasterling
+3  A: 

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.

Thomas Wouters