当装饰器是其他类的方法时,如何将未知的参数列表发送给python装饰器? [英] How can I send unknown list of arguments to a python decorator -- when the decorator is a method of a different class?

查看:99
本文介绍了当装饰器是其他类的方法时,如何将未知的参数列表发送给python装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与 另一个问题 我刚刚问过。

This question is related to another question I just asked.

我创建了一个python装饰器,如下所示。我希望这个装饰器接受未知的参数列表。但是还会有皱纹。装饰器是另一个类的实例方法:

I have created a python decorator as shown below. 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)

如何修复它?

推荐答案

这是我编码装饰器的方法:

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!"

这是编码装饰器的典型方法。类 A 在被调用时返回可调用对象。 A 类的可调用对象将被自动调用以进行装饰。调用可调用对象时,其 __ call __ 方法被触发,其 __ call __ 运算符重载方法在执行后返回包装函数一些定制。包装函数是将逻辑包装在原始函数周围的函数。

This is a typical way of coding decorators. Class A returns a callable object when called. The callable object of class A will be called automatically for decoration. 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. The wrapper function is the function that wraps logic around your original function.

这篇关于当装饰器是其他类的方法时,如何将未知的参数列表发送给python装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆