Class constants in python

nodwj picture nodwj · May 20, 2012 · Viewed 197k times · Source

In python, I want a class to have some "constants" (practically, variables) which will be common in all subclasses. Is there a way to do it with friendly syntax? Right now I use:

class Animal:
    SIZES=["Huge","Big","Medium","Small"]

class Horse(Animal):
    def printSize(self):
        print(Animal.SIZES[1])

and I'm wondering if there is a better way to do it or a way to do it without then having to write "Animal." before the sizes. Horse inherits from Animal.

Answer

betabandido picture betabandido · May 20, 2012

Since Horse is a subclass of Animal, you can just change

print(Animal.SIZES[1])

with

print(self.SIZES[1])

Still, you need to remember that SIZES[1] means "big", so probably you could improve your code by doing something like:

class Animal:
    SIZE_HUGE="Huge"
    SIZE_BIG="Big"
    SIZE_MEDIUM="Medium"
    SIZE_SMALL="Small"

class Horse(Animal):
    def printSize(self):
        print(self.SIZE_BIG)

Alternatively, you could create intermediate classes: HugeAnimal, BigAnimal, and so on. That would be especially helpful if each animal class will contain different logic.