You need __new__()
for that. (And you also need to make it a new-style class, assuming you're using Python 2, by subclassing object
.)
class ClassA(object):
def __new__(cls,theirnumber):
if theirnumber > 10:
# all big numbers should be ClassB objects:
return ClassB.ClassB(theirnumber)
else:
# numbers under 10 are ok in ClassA.
return super(ClassA, cls).__new__(cls, theirnumber)
__new__()
runs as part of the class instantiation process before __init__()
. Basically __new__()
is what actually creates the new instance, and __init__()
is then called to initialize its properties. That's why you can use __new__()
but not __init__()
to alter the type of object created: once __init__()
starts, the object has already been created and it's too late to change its type. (Well... not really, but that gets into very arcane Python black magic.) See the documentation.
In this case, though, I'd say a factory function is more appropriate, something like
def thingy(theirnumber):
if theirnumber > 10:
return ClassB.ClassB(theirnumber)
else:
return ClassA.ClassA(theirnumber)
By the way, note that if you do what I did with __new__()
above, if a ClassB
is returned, the __init__()
method you wrote in ClassA
will not be called on the ClassB
instance! When you construct the ClassB
instance inside ClassA.__new__()
, its own __init__()
method (ClassB.__init__()
) will be run at that point, so hopefully it makes sense that Python shouldn't run another unrelated __init__()
method on the same object. But this can get kind of confusing, which is probably another argument in favor of the factory function approach.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…