python - 如何确保具有多重继承的方法调用的一定顺序?
问题描述
我正在开发一个包含以下类的包:
# 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):
...
因为在这种情况下唯一有意义的初始化顺序是:
- 首先尝试从服务器获取最新值
- 然后尝试我们是否有一些保存的值
- 使用默认值作为最后的手段
我想实现这一点:
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
解决方案
推荐阅读
- string - 如何使用 HELM-3 值多行字符串
- angular - 应该如何编写或实现此接口以避免目标仅允许 1 的 TS2322 错误
- flutter - 将 Flutter 的 MaterialApp 放入 Container
- ruby-on-rails - Rails - 范围和多对多关系
- html - 如何将数据库建模为动态 HTML 表单?
- python - 取字符串数字列表的最大值
- roomle - 不应显示价格
- php - 在 WooCommerce 购物车中购买一个、折扣另一个产品的问题
- java - maven-assembly-plugin:3.1.1 未找到
- c# - Ef 代码第一个错误:EntityType: 'ModelName' has no key defined