首页 > 解决方案 > 如何确保具有多重继承的方法调用的一定顺序?

问题描述

我正在开发一个包含以下类的包:

# pseudo-code
class Block:
    def start(self):
        if not initialized:
            initialze_from_default # fail-safe

class BlockPersistent(Block):
    def start(self):
        if not initialized:
            initialze_from_saved_state # does nothing if no state was saved
        super().start()

class BlockRemote(Block):
    def start(self):
        if not initialized:
            initialze_from_remote_server # does nothing if network I/O fails
        super().start()

应用程序可以使用这三个类中的任何一个作为自己的类的基础。但是当应用程序代码要定义一个同时支持客户端/服务器通信和持久状态的块时,必须注意正确的顺序:

class SomeBlock(BlockRemote, BlockPersistent):
    ...

因为在这种情况下唯一有意义的初始化顺序是:

  1. 首先尝试从服务器获取最新值
  2. 然后尝试我们是否有一些保存的值
  3. 使用默认值作为最后的手段

我想实现这一点:

class SomeBlock(BlockPersistent, BlockRemote): # wrong order!

也会以正确的顺序调用所有start函数(或者至少失败并显示关于错误顺序的明确错误消息)。我的问题有什么推荐的方法吗?


我希望我能得到一些有用的反馈。如果不是,我可能会实现这样的事情:

class Block:
    def _init_subclass(cls, ...)
        super()._init_subclass(...)
        # recursively visit all cls.__bases__,
        # collect all _start methods,
        # sort by PRIORITY (from highest to lowest)
        cls.starts = [...]

    def start(self):
        for func in self.starts:
            func(self)

    PRIORITY = 0
    def _start(self):
        if not initialized:
            initialze_from_default # fail-safe

class BlockPersistent(Block):
    PRIORITY = 10
    def _start(self):
        if not initialized:
            initialze_from_saved_state # does nothing if no state was saved

class BlockRemote(Block):
    PRIORITY = 20
    def _start(self):
        if not initialized:
            initialze_from_remote_server # does nothing if network I/O fails

标签: python

解决方案


推荐阅读