简体   繁体   English

一个方法可以是同一个类的另一个方法的装饰器吗?

[英]Can a method be a decorator of another method of the same class?

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) Here is the problem. (1)这是问题所在。 I want to use the DullRepetitiveClass.mydecorator method to decorate the somemethod method. 我想使用DullRepetitiveClass.mydecorator方法来修饰somemethod方法。 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? 有一个简单的方法吗?

EDIT: Ok, the answer is quite obvious. 编辑:好的,答案很明显。 As Sven puts it below, the decorator itself just transform the method. 正如Sven所说,装饰器本身只是改变了方法。 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

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. 它不会作为self参数传递一个实例 - 在调用decorator时,甚至没有创建类,更不用说类的实例了。 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() . 该实例将作为第一个参数传递给装饰函数,因此您应该将self作为第一个参数包含在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. 您可以这样做,但您也可以在模块范围内使用它。

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

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