I have a base class and some subclasses that inherit from it. On these subclasses, I define a static property. I'd like to define another static property in the base class whose value is based on the subclass's static property's value.
Here is a toy example of what I'm referring to:
Imagine I have a few constants defined somewhere:
SERVICE_ID_TACO_BELL = 1
SERVICE_ID_T_MOBILE = 2
SERVICE_NAMES = {
SERVICE_ID_TACO_BELL: "Taco Bell",
SERVICE_ID_T_MOBILE: "T-Mobile",
}
And then I want to define my base class and some sub classes:
class BaseService(object):
service_id = None
@classmethod
def get_service_name(cls):
return SERVICE_NAMES.get(cls.service_id)
class TacoBell(BaseService):
service_id = SERVICE_ID_TACO_BELL
Right now we can do this:
assert TacoBell.service_id == SERVICE_ID_TACO_BELL
assert TacoBell.get_service_name() == "Taco Bell"
The goal is to be able to do this:
assert TacoBell.service_name == "Taco Bell"
We can do something like this after the fact:
setattr(TacoBell, 'service_name', TacoBell.get_service_name())
but that feels messy
How can we add a static, yet dynamic property to BaseService
that checks the subclass's service_id
property against SERVICE_NAMES
to return the value?
I have a feeling that the solution is metaclasses.