通过勤奋地搜索StackOverflow,我found out如何做到这一点。您使用inspect模块。在import inspect
def make_wrapper(fn):
arg_names = inspect.getargspec(fn)[0]
def wrapped_fn(*args, **kwargs):
# mydict now gets all expected positional arguments:
mydict = dict(tup for tup in zip(arg_names, args))
# special name "__args" gets list of all positional arguments
mydict["__args"] = args
# mydict now updated with all keyword arguments
mydict.update(kwargs)
# mydict now has full information on all arguments of any sort
print("TEST: mydict: %s" % str(mydict))
return fn(*args, **kwargs)
return wrapped_fn
def foo(a, b, c, *args, **kwargs):
# a, b, and c must be set; extra, unexpected args will go in args list
return a + b + c
foo = make_wrapper(foo)
foo(3, 5, 7, 1, 2)
# prints: TEST: mydict: {'a': 3, 'c': 7, 'b': 5, '__args': (3, 5, 7, 1, 2)}
# returns: 15
这就是你所说的问题的完美解决方案。它是一个包装器,不需要传入参数,它应该适用于任何函数。如果您需要它来处理类对象或其他东西,您可以阅读inspect的文档并了解如何操作。在
请注意,字典中当然不会保留顺序,因此您可能看不到我测试时看到的确切顺序。但dict中应该有相同的值