Suppose I have a class Fruit and two Subclasses of it Orange(Fruit) and Banana(fruit)
Fruit has an initializer, and I pass some parameters to it. But I don't want it to just create and return a fruit necessarily, but based upon the parameters passed to it, to possibly return one of several different subclasses of it. For example:
Fruit(color="yellow") might return a Banana object whereas Fruit(color="orange") would return an Orange.
How can I do this? I can't do it in __init__ because the class has already been created. I tried doing it in __new__ but this wound up messy because my could would create the subclass (as expected), but would then wind-up recursivley calling the Superclass's __new__.
My workaround has been to just define a Fruit.create() static method which creates the appropriate subclass, but this seems a little un-Pythonic.
Is there a "correct" way to do this?
var = foo()where foo is a class but end up returning not an instance offoofrom its init but an instance ofbar. however calling a factory method in fruit to get a subclass makes sense