简体   繁体   中英

How can I apply decorator to a superclass method in a subclass?

Say, we have the following situation,

class A():
    def something():
        ...
        ...
        ...


class B(A):
    def use_something():
        ...
        ...
        # Now, at this point I want something() to be decorated with a 
        # decorator. But, since it is already defined in base class, 
        # I am not getting how to decorate it here, in the subclass.
        self.something()
        ...
        ...

Now, in Class B, I want to use something() from Class A, but I want to apply a decorator to it. I cannot decorate it in class A, since there are different decorators that I want to apply at different places. Say, Class C(A) and I want to use something() here as well, with a different decorator.

So, coming back to the original question; how can I apply decorator to a superclass's method in a subclass?

Here you go (with params and without):

def simple_dec(func):
    def wrapped(*args, **kwargs):
        return 'No way'
    return wrapped


def simple_dec_params(first_param, second_param):
    def dec(func):
        def wrapped(*args, **kwargs):
            return '{} {}'.format(first_param, second_param)
        return wrapped
    return dec


class A():
    def something(self):
        print 'Something'


class B(A):
    def use_something(self):
        first_param = 'No'
        second_param = 'Way'
        print simple_dec(self.something)()
        print simple_dec_params(first_param, second_param)(self.something)()


b = B()
b.use_something()

Any particular reason why you can't just override something() ?

class A():
    def something(self):
        ...

class B(A):
    def use_something(self):
        ...
        self.something()
        ...

    def something(self):
        # Do "decorator" stuff
        super().something()
        # Do more "decorator" stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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