Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace an instance in __init__() with a different object?

Tags:

python

oop

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 argument to __init__() ('self' in the example below) within __init__() but it doesn't seem to do what I want.

in main:

import ClassA

my_obj = ClassA.ClassA(500)
# unfortunately, my_obj is a ClassA, but I want a ClassB!

in ClassA/__init__.py:

import ClassB

class ClassA:
    def __init__(self,theirnumber):
        if(theirnumber > 10):
            # all big numbers should be ClassB objects:
            self = ClassB.ClassB(theirnumber)
            return
        else:
            # numbers under 10 are ok in ClassA.
            return

in ClassB/__init__.py:

class ClassB:
    pass
like image 587
sneak Avatar asked Jul 09 '10 01:07

sneak


3 Answers

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.

like image 121
David Z Avatar answered Oct 07 '22 01:10

David Z


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)
like image 34
Sam Dolan Avatar answered Oct 07 '22 02:10

Sam Dolan


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.

like image 15
Ned Batchelder Avatar answered Oct 07 '22 03:10

Ned Batchelder