python - 如何在继承树中多次包装子方法?

标签 python python-3.x inheritance design-patterns frameworks

在框架中,我经常想提供框架用户子类的基类。基类提供对基类的受控访问。实现此目的的一种方法是提供具有不同名称的未实现方法,例如通过添加下划线作为前缀:

class Base:

    def method(self, arg):
        # ...
        result = self._method(arg)
        # ...
        return result

    def _method(self, arg):
        raise NotImplementedError

但是,这个方案只适用于一层继承。对于更多级别,不同的方法名称使得很难对正在发生的事情保持概览。此外,框架用户必须根据他选择的基类重写不同的方法:

class Base:

    def method(self, arg):
        # ...
        result = self._method_sub(arg)
        # ...
        return result

    def _method_sub(self, arg):
        raise NotImplementedError

class Intermediate(Base):

    def _method_sub(self, arg):
        # ...
        result = self._method_sub_sub(arg)
        # ...
        return result

    def _method_sub_sub(self, arg):
        raise NotImplementedError

当基方法需要访问子方法的返回值时,调用超方法没有帮助。我觉得面向对象有点缺陷,缺少允许将调用转发给子类的 child 关键字。有什么解决方案可以解决这个问题?

最佳答案

这给了你想要的吗?

import abc

class Base(object):
    __metaclass__ = abc.ABCMeta

    def calculate(self):
        result = self.doCalculate()
        if 3 < result < 7: # do whatever validation you want
            return result
        else:
            raise ValueError()

    @abc.abstractmethod
    def doCalculate(self):
        pass

class Intermediate(Base):
    __metaclass__ = abc.ABCMeta

class Leaf(Intermediate):
    def doCalculate(self):
        return 5

leaf = Leaf()
print leaf.calculate()

关于python - 如何在继承树中多次包装子方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39072269/

相关文章:

python - 可变移动平均线

c++ - 为什么我必须通过this指针访问模板基类成员?

javascript - Javascript 中可以继承模块吗?

Java继承和重写方法——修饰符的影响

来自同一文件夹的 python __import__ 失败

python - 在不阻塞进程的情况下启动 scrapy multiple spider

python - pandas 或 python 相当于 tidyr complete

python - Scraper 收集了很少的标题并忽略了其余的

python - Django:REST 框架登录路由的反向不起作用

python - scipy.sparse.csr_matrix 如果不​​为零则替换值