指定された関数名を動的に生成する関数

2646 ワード

https://stackoverflow.com/questions/13184281/python-dynamic-function-creation-with-custom-names
 
def bindFunction1(name):
    def func1(*args):
        for arg in args:
            print arg
        return 42 # ...
    func1.__name__ = name
    return func1

def bindFunction2(name):
    def func2(*args):
        for arg in args:
            print arg
        return 2142 # ...
    func2.__name__ = name
    return func2
 
 
反射の方法
 
class FunctionTemplate(object):
    def __init__(self):
        self.__dict__={}
    def __getattr__(self,attr):
        def p(*args):
            print ("Function name: %s, No. of args: %d"%(attr,len(args)))
            return
        self.__dict__[attr]=p
        return p

fnames=["func1","func2","func3"]
x=FunctionTemplate()
a=[getattr(x,i) for i in fnames]
 
転載先:https://www.cnblogs.com/clemente/p/10405066.html