Skip to content

Instantly share code, notes, and snippets.

@loisaidasam loisaidasam/1_problem.py
Last active Oct 5, 2018

Embed
What would you like to do?
Python help! How to make a static, yet dynamic, property in a base class?
SERVICE_ID_TACO_BELL = 1
SERVICE_ID_T_MOBILE = 2
SERVICE_NAMES = {
SERVICE_ID_TACO_BELL: "Taco Bell",
SERVICE_ID_T_MOBILE: "T-Mobile",
}
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?
SERVICE_ID_TACO_BELL = 1
SERVICE_ID_T_MOBILE = 2
SERVICE_NAMES = {
SERVICE_ID_TACO_BELL: "Taco Bell",
SERVICE_ID_T_MOBILE: "T-Mobile",
}
class ServiceMetaClass(type):
def __init__(cls, *args, **kwargs):
type.__init__(cls, *args, **kwargs)
cls.service_name = cls.get_service_name()
class BaseService(object):
__metaclass__ = ServiceMetaClass
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
# All things go
assert TacoBell.service_id == SERVICE_ID_TACO_BELL
assert TacoBell.get_service_name() == "Taco Bell"
assert TacoBell.service_name == "Taco Bell"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.