tags:

views:

72

answers:

3

I have a following class:

class Foo:
    CONSTANT = 1

    def some_fn(self):
        a = Foo.CONSTANT
        # do something

How can I refer to Foo.CONSTANT without referring to Foo, or refer to Foo in a generic way? (I don't want to change all references to it when renaming a class)

+1  A: 

Is there any reason why self.CONSTANT doesn't suit your needs?

class Foo:
    CONSTANT = 1

    def some_fn(self):
        a = self.CONSTANT
        # do something
twneale
+4  A: 

Within a method of class Foo or any subclass thereof, self.CONSTANT will refer to the value defined for that class attribute in class Foo (unless it's overridden in a subclass or in the instance itself -- if you assign self.CONSTANT=23, it's the instance attribute that's created with that value, and it overrides the class attribute in future references).

Alex Martelli
For some reason I did not think of the obvious first.
Alex B
Unless he refers to it using `self.__class__.CONSTANT`. That way, the reassignment is still bound to the class variable, and not overridden (if this is indeed the desired behavior). ;-)
Santa
@Santa, if the instance is of a derived class from `Foo`, `self.__class__.CONSTANT = 23` will create or rebind that attribute on the _derived_ class, **not** rebind `Foo`'s -- so things are a bit more delicate than you describe them.
Alex Martelli
+1  A: 

In your example, self.CONSTANT will work, but if you ever assign to self.CONSTANT, that will "override" the value defined on the class.

You can use self.__class__.CONSTANT to always refer to the value defined on the class. You can even assign to that.

Jason Diamond
It's CONSTANT, he shouldn't be assigning to it.
Wallacoloo
The only constant is change. =)
Jason Diamond