简体   繁体   English

当装饰器是其他类的方法时,如何将未知的参数列表发送给python装饰器?

[英]How can I send unknown list of arguments to a python decorator — when the decorator is a method of a different class?

This question is related to another question I just asked. 这个问题与我刚才问的另一个问题有关。

I have created a python decorator as shown below. 我创建了一个python装饰器,如下所示。 I want this decorator to accept an unknown list of arguments. 我希望这个装饰器接受未知的参数列表。 But there is an added wrinkle. 但是还会有皱纹。 The decorator is an instance method of another class: 装饰器是另一个类的实例方法:

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


class A:

    def my_decorator(self, func=None, **kwargs):

        def inner_function(decorated_function):

            def wrapped_func(*fargs, **fkwargs):
                print kwargs
                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(arg_1="Yolo", arg2="Bolo")
    def my_func():
         print "Woo Hoo!"


my_B = B()
B.my_func()

But this code below doesn't work: 但是下面的代码不起作用:

Traceback (most recent call last):
  File "./decorator_test.py", line 30, in <module>
    B.my_func()
TypeError: unbound method wrapped_func() must be called with B instance as first argument (got nothing instead)

How to fix it? 如何解决?

Here's my approach to coding your decorator: 这是编码装饰器的方法:

class A:
    def __init__(self, func=None, **kargs):
        self.args  = func
        self.kargs = kargs 
    def __call__(self, decorated_function): 
        def wrapper_func(*args, **kargs):
            print kargs
            return decorated_function(*args, **kwargs)
        if self.func:
            #..do something..
            return wrapper_func
        elif 'xyz' in self.kargs:
            #...do something else here..
            return wrapper_func
        else:
            ...


class B:
    @A(arg_1="Yolo", arg2="Bolo")              # A(...)(my_func)
    def my_func():
        print "Woo Hoo!"

This is a typical way of coding decorators. 这是编码装饰器的典型方法。 Class A returns a callable object when called. A在被调用时返回可调用对象。 The callable object of class A will be called automatically for decoration. A类的可调用对象将被自动调用以进行装饰。 When the callable object is called, its __call__ method gets triggered and its __call__ operator overloading method returns the wrapper function after performing some customization. 调用可调用对象时,将触发其__call__方法,并且其__call__运算符重载方法在执行某些自定义后将返回包装函数。 The wrapper function is the function that wraps logic around your original function. 包装函数是将逻辑包装在原始函数周围的函数。

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

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