[Tutor] Creating instance of child classes dynamically

dn PyTutor at DancesWithMice.info
Sun Feb 7 13:39:05 EST 2021


On 08/02/2021 06.52, Alan Gauld via Tutor wrote:
> On 07/02/2021 15:18, Sachit Murarka wrote:
>> I meant base class in a different python file. It was a typo.
>>
>> Example :
>>
>> parent.py
>> class Parent():
>>     @abstractmethod
>>     def process(self):
>>
>> child1.py
>> class Child1():
>>       def process(self):
>>           #Doing something
>>
>> child2.py
>> class Child2():
>>       def process(self):
>>           #Doing something else
>>
>>
>> My use case is , Parent will define the template. On the run type user will
>> pass a string , eg String will be child1 or child2 etc. Accordingly we want
>> to call process function of that class.
> 
> OK, that's all pretty standard although a dictionary of functions
> keyed by string is probably a more effective way to do it.
> 
>> Please note each child class is in a different file . In actual solution
>> there will be many children and we can not put all children in a single py
>> file.
> 
> Best practice in Python is to keep related classes in a single
> module to minimize dependencies. But you don;t want a huge number of
> classes in a single module, I agree.
> 
>> As using reflections we can create objects at run time by giving fully
>> qualified class names(Atleast in java). I have worked in Java not in Python
>> much, so trying to achieve something similar.  In java we used to do this:
>>
>> String input="Child1";
>> Parent p = Class.forName(input);
>> p.process() // this will call the method of base class which was stored in
> 
> In Pyton classes are objects so you can just assign the class to a
> variable or put it in a dictionary so:
> 
> import child1, child2
> # Store classes
> classes = { "Child1": child1.Child1(), "Child2": child2.Child2,...}
> 
> classname = "Child1"
> classes["Child1"]().process()  # calls process on an instance of Child1
> 
> But as I said functions might be more effective here:
> 
> def func1():...
> def fuc2():...
> etc...
> 
> funcs = {"Child1":func1,"Child2":func2
> 
> funcs[input]()
> 
> There's no point in creating classes just for the sake of it.
> OTOH if your classes have several other methods than just
> process() and they share the common data of the instance
> then they might make sense.


Left to my own devices, I would almost-certainly follow @Alan's approach.

As an *ex-*Java programmer, this reference may be of-interest:
https://pythonspot.com/factory-method/
-- 
Regards,
=dn


More information about the Tutor mailing list