2

I would like to change how instance variables are treated in my class based on one of my input parameters.

Here's a sense of what I'm trying to do:

from helpers import Helper1, Helper2

class MainClass:
    def __init__(self, var1, var2, category):
        self.var1 = var1
        self.var2 = var2
        self.helperType = self._get_helper(category)

        # from here I need helperType to define how var1 and var2 are processed further

    def _get_helper(self, category):
        if category == 'type1':
            return Helper1()
        elif category == 'type2':
            return Helper2()

I plan on continuously adding more helper types that handle slightly different circumstances and would prefer to keep their logic separate rather than bloat my MainClass with custom code for each instance. For example, var1 is always a string, some types may necessitate that it is reversed, others may capitalise it.

Elsewhere I want to be able to create instances of MainClass that dynamically set their properties based on the category argument, but details of what's going on inside are irrelevant so I'm trying to contain it in MainClass.

I'm confident I could get this done a number of ways but none of my ideas seem particularly clean or robust. I've looked at a few potential options like monkey-patching, inheritance and class decorators but I'm not sure they fit my needs.

Perfectly happy to be told this is a bone-headed approach so long as there's a solution attached.

P.Ackland
  • 53
  • 4
  • why not directly pass the class object as a category directly? – sahasrara62 Jul 07 '21 at 13:08
  • 1
    `self.processVar1 = self.helperType.PrVar1` , `self.processVar2 = self.helperType.PrVar2` , assign functions from your helperType to names of your class that you then use. seems to me like `category` is just a "pattern" to decide wich instance to be created (AbstractFactoryPattern) to provide a certain instance that does stuff. might be lots of better ways to do that. Seems a roundaboutway to try to do IoC together with a servicelocator without using any preset ones. – Patrick Artner Jul 07 '21 at 13:09
  • 1
    Maybe this helps: https://stackoverflow.com/questions/26243005/can-python-do-di-seamlessly-without-relying-on-a-service-locator or this https://stackoverflow.com/questions/2461702/why-is-ioc-di-not-common-in-python – Patrick Artner Jul 07 '21 at 13:12
  • @PatrickArtner I think you're right. I might just create a method within `MainClass` for handling the different cases, rather than trying so hard to separate the logic. Thanks for the tips. – P.Ackland Jul 08 '21 at 01:13

0 Answers0