Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining constants in python class, is self really needed?

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

like image 244
Theodor Avatar asked Oct 22 '10 09:10

Theodor


People also ask

Is self necessary in Python class?

self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes.

Is self optional in Python?

Writing this parameter as self is merely a convention. It is not a keyword and has no special meaning in Python. We could use other names (like this) but I strongly suggest you not to. Using names other than self is frowned upon by most developers and degrades the readability of the code ("Readability counts").

Why do you put self in Python?

The self keyword is used to represent an instance (object) of the given class. In this case, the two Cat objects cat1 and cat2 have their own name and age attributes. If there was no self argument, the same class couldn't hold the information for both these objects.

Should you use constants in Python?

A constant is a type of variable that holds values, which cannot be changed. In reality, we rarely use constants in Python. Constants are usually declared and assigned on a different module/file. Then, they are imported to the main file.


1 Answers

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.

like image 92
Thomas Wouters Avatar answered Sep 20 '22 11:09

Thomas Wouters