Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : creating dynamic functions

Tags:

python

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

like image 347
ifixthat Avatar asked Jan 03 '11 06:01

ifixthat


2 Answers

With closures.

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

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

caveats

like image 179
Ignacio Vazquez-Abrams Avatar answered Nov 11 '22 19:11

Ignacio Vazquez-Abrams


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' 
like image 36
amccormack Avatar answered Nov 11 '22 20:11

amccormack