Alex Rivera | Logout

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

Asked 2010-07-09T01:25:08.857
29

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
Edit
Report

1 Answer

23

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)
answered 2010-07-09T01:30:51.790

Your Answer