Skip to content

Instantly share code, notes, and snippets.

@subhashb
Last active August 27, 2020 21:22
Show Gist options
  • Save subhashb/adb75a3a05a611c3d9193da695d46dd4 to your computer and use it in GitHub Desktop.
Save subhashb/adb75a3a05a611c3d9193da695d46dd4 to your computer and use it in GitHub Desktop.
Add properties dynamically to class
from collections import defaultdict
from enum import Enum
class ElementTypes(Enum):
PHONE = "PHONE"
CAR = "CAR"
class Registry:
def __new__(cls, *args, **kwargs):
cls.setup_properties()
instance = super(Registry, cls).__new__(cls, *args, **kwargs)
return instance
def __init__(self):
self._elements = defaultdict(list)
def register(self, element_type, item):
self._elements[element_type.value].append(item)
def get(self, element_type):
return self._elements[element_type.value]
@classmethod
def setup_properties(cls):
for item in ElementTypes:
prop_name = item.value
prop = property(lambda self: self.get(item))
setattr(Registry, prop_name.lower(), prop)
registry = Registry()
registry.register(ElementTypes.PHONE, "phone1")
registry.register(ElementTypes.PHONE, "phone2")
registry.register(ElementTypes.CAR, "car1")
registry.register(ElementTypes.CAR, "car2")
print(f"Registry holds all elements: {registry._elements}")
print(f"Registry has properties too: {dir(registry)}")
# Should print phones and cars, but only prints cars
print(f"Printing car: {registry.car}")
print(f"Printing phones: {registry.phone}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment