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

后端 未结 3 690
Happy的楠姐
Happy的楠姐 2020-12-03 01:30

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

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 02:00

    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)
    

提交回复
热议问题