Skip to content

Instantly share code, notes, and snippets.

@byroot
Created November 19, 2011 16:13
Show Gist options
  • Select an option

  • Save byroot/1379001 to your computer and use it in GitHub Desktop.

Select an option

Save byroot/1379001 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
class ItemMetaClass(type):
ITEM_CLASSES_INDEX = {}
def __new__(mcs, name, bases, dict):
cls = type.__new__(mcs, name, bases, dict)
if hasattr(cls, 'id'):
mcs.ITEM_CLASSES_INDEX[cls.id] = cls
return cls
class Item(object):
__metaclass__ = ItemMetaClass
def __new__(cls, id=None, *args, **kwargs):
if id in ItemMetaClass.ITEM_CLASSES_INDEX:
return ItemMetaClass.ITEM_CLASSES_INDEX[id](*args, **kwargs)
else:
return super(Item, cls).__new__(cls)
class Hache(Item):
id = 12
class Foo(Item):
id = 42
print Item(12)
print Item(42)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment