1 回答
TA贡献1891条经验 获得超3个赞
你尝试过吗?
如果您将import语句放在上面所示的方法中__init__,则不会出现“循环依赖”:在第一次导入另一个模块时,定义 ComManager 的调用者模块已经运行,并且该类已定义并准备好在第二个模块中导入。
除此之外,您可以将处理方法放在 mixin 类中,而不是放在处理程序ComManager本身的主体中。
因此,在另一个模块中,您将拥有:
...
class ID(IntEnum):
...
class HandlersMixin:
def _rcv_message_x(self, msg):
...
...
mapping = {
ID.message_x = HandlerMixn._rcv_message_x,
}
请注意,通过这种方式,映射映射了未绑定的方法:它们是普通函数,需要“HandlerMixin”实例作为其第一个参数
在你的第一个模块上:
from other_module import ID, mapping, HandlerMixin
class ComManager(HandlerMixin):
def _rcv_thread(self):
message_id = self.rcv_message_id() # receive message ID from socket
message_id = ID(message_id) # Change from type "int" to type "ID"
mapping[message_id](self)
# Passing "self" explictly will make the methods work the same
# as f they were called from this instance as `self.method_name`,
# and since they are methods on this class through inheritance
# they can use any other methods or attributes on this instance
添加回答
举报