Created
November 19, 2011 16:13
-
-
Save byroot/1379001 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/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