抽象方法上的装饰器 [英] Decorators on abstract methods

查看:45
本文介绍了抽象方法上的装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,有没有一种方法可以使抽象方法上的装饰器传递给派生的实现?

In python, is there a way to make a decorator on an abstract method carry through to the derived implementation(s)?

例如,在

import abc

class Foo(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    @some_decorator
    def my_method(self, x):
        pass

class SubFoo(Foo):
    def my_method(self, x):
        print x

据我所知,

SubFoo my_method 不会被 some_decorator 装饰.有什么方法可以实现此目的而不必单独装饰 Foo 的每个派生类?

SubFoo's my_method won't get decorated with some_decorator as far as I can tell. Is there some way I can make this happen without having to individually decorate each derived class of Foo?

推荐答案

我会将其编码为两种不同的方法,就像在标准方法工厂模式描述中一样.

I would code it as two different methods just like in standard method factory pattern description.

https://www.oodesign.com/factory-method-pattern.html

class Foo(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    @some_decorator
    def my_method(self, x):
        self.child_method()

class SubFoo(Foo):
    def child_method(self, x):
        print x

这篇关于抽象方法上的装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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