I am calling a constructor in ClassA and want to have the resulting object be of a different class (ClassB) if a certain condition is met. I\'ve tried replacing the first a
Don't try to pervert the purpose of constructors: use a factory function. Calling a constructor for one class and being returned an instance of a different class is a sure way to cause confusion.
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 of the ClassB
instance will not be called! Python only calls __init__()
if the object returned from __new__()
is an instance of the class in which the __new__()
method is contained (here ClassA
). That's another argument in favor of the factory function approach.
I would suggest using a factory pattern for this. For example:
def get_my_inst(the_number):
if the_number > 10:
return ClassB(the_number)
else:
return ClassA(the_number)
class_b_inst = get_my_inst(500)
class_a_inst = get_my_inst(5)