I am wondering if the following strategy is a proper/pythonic way to create a dynamic function within a method. The goal is to have a class that can calculate a value based on a complex model defined by FUN()
, but I want to be able to change that model within a script without rewriting it, or creating a bunch of different types of classes (since this function is the only thing that I expect to change).
I also read in a response to this question that the way I have it structured may end up being slower? I intend to call setupFunction()
1 to 3 times a simulation (changing the model) and call FUN
many thousands of times.
Pseudocode...
class MyClass:
def __init__(self, model = 'A'):
self.setupFunction(model)
# Other Class Stuff...
def setupFunction(self, _model):
if _model == 'A':
def myFunc(x):
# Do something with x, store in result
return result
else:
def myFunc(x):
# Do something different with x
return result
self.FUN = myFunc
# Other Class Methods... some of which may call upon self.FUN
Model1 = MyClass('A')
Model2 = MyClass('B')
print(Model1.FUN(10))
print(Model2.FUN(10))
I have done some minor tests and the above seems to not break upon first glance. I know I could also do something similar by doing the following instead, but then it will have to test for the model on each call to FUN()
and I will have many different model cases in the end:
class MyClass():
def __init__(self, model = 'A'):
def FUN(self, x):
if self.model == 'A':
# result = Stuff
else:
# result = Other Stuff
return result
Still new to python, so thanks for any feedback!