Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

python - 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. 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?

EDIT: 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
question from:https://stackoverflow.com/questions/65679916/using-decorator-inside-a-class-returns-typeerror-spinner-missing-1-required-p

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...