Last active
April 13, 2016 15:47
-
-
Save SpotlightKid/7918641 to your computer and use it in GitHub Desktop.
Demonstrates how to use meta-classes to build a registry of sub-classes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# | |
# registrable.py | |
# | |
"""Demonstrates how to use meta-classes to build a registry of sub-classes.""" | |
__all__ = [ | |
'Registrable', | |
'RegistrableMeta', | |
'BlueColor', | |
'GreenColor', | |
'YellowColor', | |
'RedColor', | |
'BlackColor' | |
] | |
import collections | |
class RegistrableMeta(type): | |
"""Meta-class for registrable and sub-classes. | |
Holds a registry of all sub-classes. | |
""" | |
registry = collections.OrderedDict() | |
def __init__(cls, clsname, bases, classdict): | |
cls.registry[cls.tag] = cls | |
Registrable = RegistrableMeta('Registrable', (object,), {'tag': None}) | |
class BlueColor(Registrable): | |
tag = 'blue' | |
rgb = (0, 0, 255) | |
class GreenColor(Registrable): | |
tag = 'green' | |
rgb = (0, 255, 0) | |
class YellowColor(Registrable): | |
tag = 'yellow' | |
rgb = (0, 255, 255) | |
class RedColor(Registrable): | |
tag = 'red' | |
rgb = (255, 0, 0) | |
class BlackColor(Registrable): | |
tag = 'black' | |
rgb = (0, 0, 0) | |
if __name__ == '__main__': | |
cls = Registrable.registry.get('blue') | |
if cls: | |
instance = cls() | |
print(instance.rgb) | |
else: | |
print("No class found for tag 'blue'.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment