ifixthat
ifixthat

Reputation: 6295

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 how to create dynamic class:

My Structure is something like this :

class xyz:

    def Project():

       start = 2011-01-03

       def Phase1():
          effort = '2d'
       def Phase2():
          effort = '3d'
       def Phase3():
          effort = '4d'

Now want to generate those all PhaseX() function dynamically so can any one suggest me how to achieve such thing using Python Code

Waiting for Positive reply Regards Thank You

Upvotes: 11

Views: 16950

Answers (4)

teeks99
teeks99

Reputation: 3642

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.

class xyz(object):
    def __init__(self):
        # I wasn't clear how you were using effort...like this?
        self.effort = '0d'
    def add_phases(self, phase_dict): # Take a dictionary of phases and values
        for phase, value in phase_dict.items():
            self.make_phase(phase, value)
    def make_phase(self, phase, value):
        def somephase(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'

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799470

With closures.

def makefunc(val):
  def somephase():
    return '%dd' % (val,)
  return somephase

Phase2 = makefunc(2)
Phase3 = makefunc(3)

caveats

Upvotes: 29

albertov
albertov

Reputation: 2348

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.

Upvotes: 0

amccormack
amccormack

Reputation: 13927

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?

def setEffort(n):
    effort = str(n)+'d' 

Upvotes: 1

Related Questions