为什么我可以将命名参数的列表而不是未命名的参数传递给这个装饰器?

2024-04-19 00:12:23 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题不是How pass unknown list of unnamed arguments to a python decorator?的重复问题。我在问一个不同但又相关的问题。在

我创建了一个python decoratormy_decorator方法,如下所示。我希望这个装饰器接受一个未知的参数列表:

#!/usr/bin/env python
from functools import wraps

class A:
    def my_decorator(self, func=None, *args, **kwargs):
        print "Hello World2!"
        print 'args = {}'.format(args)
        print 'kwargs = {}'.format(kwargs)
        def inner_function(decorated_function):
            def wrapped_func(*fargs, **fkwargs):
                print "Hello World3!"
                return decorated_function(*fargs, **fkwargs)
            return wrapped_func

        if func:
            return inner_function(func)
        else:
            return inner_function

class B:
    my_a = A()

    @my_a.my_decorator(a1="Yolo", b1="Bolo")
    def my_func(self):
         print "Hello World1!"

my_B = B()
my_B.my_func()

此代码运行良好:

^{pr2}$

但是,现在,我不想将命名参数传递给@my_a.my_decorator,而是希望像这样传递未命名的参数:@my_a.my_decorator('Yolo', 'Bolo'),但它失败了:

^{3}$

我该怎么解决这个问题?在


Tags: selfformathello参数returnmydefargs