Skip to content

Instantly share code, notes, and snippets.

@loisaidasam
Last active October 5, 2018 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loisaidasam/49087dee21bc59bc073f92f7475db283 to your computer and use it in GitHub Desktop.
Save loisaidasam/49087dee21bc59bc073f92f7475db283 to your computer and use it in GitHub Desktop.
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