简体   繁体   English

如何将装饰器应用于子类中的超类方法?

[英]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. 现在,在B类中,我想使用A类中的something(),但我想为其应用装饰器。 I cannot decorate it in class A, since there are different decorators that I want to apply at different places. 我无法在A类中进行装饰,因为我想在不同的地方应用不同的装饰器。 Say, Class C(A) and I want to use something() here as well, with a different decorator. 比方说,C(A)类,我也想在此处使用其他装饰器使用something()。

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): 您可以在这里(使用params和不使用params):

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() ? 有什么特殊原因导致您不能仅仅覆盖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

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

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