一个方法可以作为同一类的另一个方法的装饰器吗? [英] Can a method be a decorator of another method of the same class?

查看:74
本文介绍了一个方法可以作为同一类的另一个方法的装饰器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一门课,他们的函数上有一个乏味的重复模式,我想将此模式变成装饰器。但事实是,此装饰器必须访问当前实例的某些属性,因此我想将其转换为此类中的方法。我对此有一些问题。

I have a class with a dull repeating pattern on their functions and I wanted to turn this pattern into a decorator. But the thing is that this decorator must access some attributes of the current instance, so I wanted to turn it into a method in this class. I'm having some problems with that.

所以,这类似于我想要的:

So, this is similar to what I want:

class DullRepetitiveClass:
    def __init__(self, nicevariable):
        self.nicevariable = nicevariable

    def mydecorator(self, myfunction):
        def call(*args, **kwargs):
            print "Hi! The value of nicevariable is %s"%(self.nicevariable,)
            return myfunction(*args, **kwargs)
        return call

    @mydecorator            #Here, comment (1) below.
    def somemethod(self, x):
        return x + 1

( 1)这是问题所在。我想使用 DullRepetitiveClass.mydecorator 方法来装饰 somemethod 方法。但是我不知道如何使用当前实例中的方法作为装饰器。

(1) Here is the problem. I want to use the DullRepetitiveClass.mydecorator method to decorate the somemethod method. But I have no idea how to use the method from the current instance as the decorator.

是否有一种简单的方法?

Is there a simple way of doing this?

编辑:好的,答案很明显。正如Sven所说的那样,装饰器本身只是在改变方法。方法本身应该处理与实例有关的所有事情:

Ok, the answer is quite obvious. As Sven puts it below, the decorator itself just transform the method. The method itself should deal with all things concerning the instance:

def mydecorator(method):
    def call(self, *args, **kwargs):
        print "Hi! The value of nicevariable is %s"%(self.nicevariable,)
        return method(self, *args, **kwargs)
    return call


class DullRepetitiveClass:
    def __init__(self, nicevariable):
        self.nicevariable = nicevariable

    @mydecorator            
    def somemethod(self, x):
        return x + 1


推荐答案

装饰器仅获取一个参数-装饰的函数或方法。它不会作为 self 参数传递实例–在调用装饰器时,甚至还没有创建类,更不用说该类的实例了。实例将作为第一个参数传递给装饰函数,因此您应在 call()的参数列表中将 self 作为第一个参数。 code>。

The decorator gets only one parameter – the function or method it decorates. It does not get passed an instance as self parameter – at the moment the decorator is called, not even the class has been created, let alone an instance of the class. The instance will be passed as first argument to the decorated function, so you should include self as first parameter in the parameter list of call().

我认为没有必要在类范围中包含装饰器。您可以做到这一点,但也可以在模块范围内使用它。

I don't see the necessity to include the decorator in the class scope. You can do this, but you can just as well have it at module scope.

这篇关于一个方法可以作为同一类的另一个方法的装饰器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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