Created
March 30, 2010 07:30
-
-
Save keturn/348872 to your computer and use it in GitHub Desktop.
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
from django.db import models | |
class Top(models.Model): | |
_counter = 0 | |
def __init__(self, arg): | |
Top._counter += 1 | |
print "Top(%s)#__init__(<%x>, %s) called %d times" % ( | |
self.__class__.__name__, id(self), arg, Top._counter) | |
def newA(cls, *args, **kwargs): | |
print "O HAI %sx%x.__new__(%s, %s, %s)" % ( | |
cls.__name__, id(cls), cls, args, kwargs) | |
if cls is A and len(args) > 0: | |
fav = args[0] | |
newcls = clsmap.get(fav) | |
if newcls: | |
return newcls.__new__(newcls, *args, **kwargs) | |
else: | |
print "PRETENDING TO BE ABSTRACT" | |
return None # or raise? | |
else: | |
return super(A, cls).__new__(cls, *args, **kwargs) | |
class A(Top): | |
pass | |
# THIS IS THE TRICK! O.o | |
A.__new__ = staticmethod(newA) | |
class B(A): | |
fav = 1 | |
class C(A): | |
fav = 2 | |
# could build this automagically with some A.__subclasses__() stuff maybe. | |
clsmap = { | |
B.fav: B, | |
C.fav: C | |
} | |
assert A(0) is None | |
b = A(1) | |
assert isinstance(b, B) | |
c = A(2) | |
assert isinstance(c, C) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment