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
添加回答
舉報