简体   繁体   English

装饰器函数使用 *args 和 **kargs 作为其 __call__ 方法的参数,

[英]Decorator function using *args and **kargs as parameters for its __call__ method,

I'm currently working with a decorated function that is supposed to check a function's annotations if a certain bool is set to True in the decorator class.我目前正在使用一个装饰函数,如果在装饰器类中将某个 bool 设置为 True,该函数应该检查函数的注释。 What I'm a bit confused about is the decorator function's __call__ method header:我有点困惑的是装饰器函数的__call__方法头:

def __call__(self, *args, **kargs):

and its parameter list.及其参数列表。

I understand that its parameters *args and **kargs are used for the arguments provided to the function, but in the problem I'm dealing with I have to call the original function (which is an attribute in the instance object created from the decorator class named _f ).我知道它的参数*args**kargs用于提供给函数的参数,但是在我正在处理的问题中,我必须调用原始函数(这是从装饰器创建的实例对象中的一个属性名为_f类)。

How would I go about calling _f with the arguments provided to the decorated function?我将如何使用提供给装饰函数的参数来调用_f Should I check to see whether args / kargs is empty and call self._f(args) / self._f(kargs) for the nonempty parameter?我应该检查args / kargs是否为空并self._f(args)空参数调用self._f(args) / self._f(kargs)吗?

When you decorate the method:当你装饰方法时:

class Foo:

    @someDecorator
    def my_method(self, x, y):
        ...

It isn't yet actually a method;它实际上还不是一种方法; it's just a function.这只是一个函数。 Inside your decorator, you treat it as such:在你的装饰器中,你这样对待它:

def someDecorator(f):
    def _(*args, **kwargs):
        ...
        return f(*args, **kwargs)
    return _

When _ gets called, self will be included in the *args argument._被调用时, self将包含在*args参数中。

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

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