繁体   English   中英

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

[英]Why can I pass a list of named arguments — but not unnamed arguments — to this decorator?

这个问题不是“ 如何将未知的未命名参数列表传递给python装饰器?”的重复项 我在这里问一个不同但相关的问题。

我创建了一个python装饰器my_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()

这段代码可以正常工作:

Hello World2!
args = ()
kwargs = {'a1': 'Yolo', 'b1': 'Bolo'}
Hello World3!
Hello World1!

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

Hello World2!
args = ('Bolo',)
kwargs = {}
Hello World3!
Traceback (most recent call last):
  File "./decorator_test.py", line 20, in <module>
    class B:
  File "./decorator_test.py", line 23, in B
    @my_a.my_decorator('Yolo', 'Bolo')
  File "./decorator_test.py", line 12, in wrapped_func
    return decorated_function(*fargs, **fkwargs)
TypeError: 'str' object is not callable

我怎样才能解决这个问题?

def my_decorator(self, *args, **kwargs):
    [skip]
    if 'func' in kwargs:
        return inner_function(kwargs.pop('func'))
    else:
        return inner_function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM