Python : creating dynamic functions

前端 未结 4 1709
失恋的感觉
失恋的感觉 2020-12-28 21:21

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 ques

4条回答
  •  旧时难觅i
    2020-12-28 22:07

    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.

提交回复
热议问题