简体   繁体   中英

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

This question is not a duplicate of How pass unknown list of unnamed arguments to a python decorator? . I'm asking a different but related question here.

I have created a python decorator my_decorator method as shown below. I want this decorator to accept an unknown list of arguments:

#!/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()

This code works perfectly fine:

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

However, now, instead of passing named arguments to @my_a.my_decorator , I want to pass unnamed arguments like this: @my_a.my_decorator('Yolo', 'Bolo') and it fails:

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

How can I fix this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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