How to get method parameter names?

前端 未结 15 2393
眼角桃花
眼角桃花 2020-11-22 09:14

Given the Python function:

def a_method(arg1, arg2):
    pass

How can I extract the number and names of the arguments. I.e., given that I h

15条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 09:49

    Here is something I think will work for what you want, using a decorator.

    class LogWrappedFunction(object):
        def __init__(self, function):
            self.function = function
    
        def logAndCall(self, *arguments, **namedArguments):
            print "Calling %s with arguments %s and named arguments %s" %\
                          (self.function.func_name, arguments, namedArguments)
            self.function.__call__(*arguments, **namedArguments)
    
    def logwrap(function):
        return LogWrappedFunction(function).logAndCall
    
    @logwrap
    def doSomething(spam, eggs, foo, bar):
        print "Doing something totally awesome with %s and %s." % (spam, eggs)
    
    
    doSomething("beans","rice", foo="wiggity", bar="wack")
    

    Run it, it will yield the following output:

    C:\scripts>python decoratorExample.py
    Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
     'wiggity', 'bar': 'wack'}
    Doing something totally awesome with beans and rice.
    

提交回复
热议问题