Skip to content

Instantly share code, notes, and snippets.

@SpotlightKid
Last active April 13, 2016 15:47
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 SpotlightKid/7918641 to your computer and use it in GitHub Desktop.
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.
# -*- 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