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.