How to use a variable as function name in Python

前端 未结 6 1936
庸人自扰
庸人自扰 2020-12-01 16:17

Would it be possible to use a variable as a function name in python? For example:

list = [one, two, three]
for item in list:
    def item():
         some_st         


        
6条回答
  •  渐次进展
    2020-12-01 16:58

    You can do this:

    from types import FunctionType
    from copy import copy
    
    def copy_function(fn):
        return FunctionType(copy(fn.func_code), copy(fn.func_globals), name=item,
                            argdefs=copy(fn.func_defaults),
                            closure=copy(fn.func_closure))
    
    list = ['one', 'two', 'three']
    
    for item in list:
        def _fn():
            print(item)
        globals()[item] = copy_function(_fn)
    list = map(eval, list)
    

提交回复
热议问题