Python : Creating Dynamic Functions
I have issue where i want to create Dynamic function which will do some calculation based to values retrieved from database, i am clear with my internal calculation but question in
Solution 1:
With closures.
def makefunc(val):
def somephase():
return'%dd' % (val,)
return somephase
Phase2 = makefunc(2)
Phase3 = makefunc(3)
Solution 2:
This answer may be assuming your intentions are too simplistic, but it appears as if you want to set a value for particular function calls.
Would you consider something like the following?
defsetEffort(n):
effort = str(n)+'d'
Solution 3:
I recently struggled with this same issue, and I wanted to write down what I found to work for me...using the original example. The difference from the earlier answer is that I'm using setattr to make the function name (as part of the class) as well.
classxyz(object):
def__init__(self):
# I wasn't clear how you were using effort...like this?
self.effort = '0d'defadd_phases(self, phase_dict): # Take a dictionary of phases and valuesfor phase, value in phase_dict.items():
self.make_phase(phase, value)
defmake_phase(self, phase, value):
defsomephase(self): # Create a closure like @Ignacio
self.effort = str(value) + 'd'setattr(self.__class__, "Phase" + str(phase), somephase)
tracker = xyz()
phases = {1:2, 2:1, 3:6, 4:2}
tracker.add_phases(phases)
tracker.Phase3()
assert tracker.effort == '6d'
Solution 4:
You can use the type function to create a python class dynamically or a metaclass. Ill describe the first method:
myDynamicClassWithDynamicFunctions = type('ClassName', (object,), {
'phase1': aFunction,
'phase2': anotherFunction,
....})
The arguments to type are: the class name, the class bases (as a tuple), the class attributes in a dict. Of course, you can construct these parameters programmatically as you wish.
Post a Comment for "Python : Creating Dynamic Functions"