Alex B
Alex B

Reputation: 84792

How can I refer to class variable in a function without referring to its class in Python?

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)

Upvotes: 1

Views: 177

Answers (3)

Jason Diamond
Jason Diamond

Reputation: 780

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.

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881497

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

Upvotes: 4

twneale
twneale

Reputation: 2946

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

Upvotes: 1

Related Questions