我正在使用具有以下类的包进行工作:
# 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