python类之间的双向通信(已编辑并添加代码)
所以,我有需要相互交流的课程。例如,我构建了聊天程序的客户端。一个类处理套接字,另一个类处理GUI。因此GUI类必须从socket类获取接收到的数据,此外还必须通过socket类发送消息 问题是,如果让一个类包含另一个类,则无法进行双向通信。您需要将父实例传递给子实例,但我认为传递该实例不是正确的方法 最好的办法是什么 这里有一些代码,例如,希望它清楚(请阅读代码中的注释以便更好地理解):python类之间的双向通信(已编辑并添加代码),python,oop,logic,Python,Oop,Logic,所以,我有需要相互交流的课程。例如,我构建了聊天程序的客户端。一个类处理套接字,另一个类处理GUI。因此GUI类必须从socket类获取接收到的数据,此外还必须通过socket类发送消息 问题是,如果让一个类包含另一个类,则无法进行双向通信。您需要将父实例传递给子实例,但我认为传递该实例不是正确的方法 最好的办法是什么 这里有一些代码,例如,希望它清楚(请阅读代码中的注释以便更好地理解): 为什么不将SockHandler实例化为main窗口的属性呢 像这样: class MainWindow:
为什么不将
SockHandler
实例化为main窗口的属性呢
像这样:
class MainWindow:
def __init__(self, master, username, sock):
# Tkinter Code Here
self.socket_handler = SockHandler(sock)
class SockHandler:
def __init__(self, client_socket):
# nothing relevant for the Q
self.received_messages = Queue.Queue()
现在,您可以使用self.socket\u handler.send\u msg
对于接收,让套接字将接收到的数据存储在main窗口可以检索到的位置
像这样:
class MainWindow:
def __init__(self, master, username, sock):
# Tkinter Code Here
self.socket_handler = SockHandler(sock)
class SockHandler:
def __init__(self, client_socket):
# nothing relevant for the Q
self.received_messages = Queue.Queue()
现在,您需要为main窗口
提供一种访问所接收消息的方法。如果需要,您可以让它通过查询队列直接获取消息,但我更喜欢这样:
# Within the SockHandler Class
def get_next_message():
try:
return self.received_messages.get(True, 5)
except:
return None
无论是SockHandler
还是MainWindow
在此方法中处理超时异常。这取决于您。为什么不将SockHandler
实例化为主窗口的属性
像这样:
class MainWindow:
def __init__(self, master, username, sock):
# Tkinter Code Here
self.socket_handler = SockHandler(sock)
class SockHandler:
def __init__(self, client_socket):
# nothing relevant for the Q
self.received_messages = Queue.Queue()
现在,您可以使用self.socket\u handler.send\u msg
对于接收,让套接字将接收到的数据存储在main窗口可以检索到的位置
像这样:
class MainWindow:
def __init__(self, master, username, sock):
# Tkinter Code Here
self.socket_handler = SockHandler(sock)
class SockHandler:
def __init__(self, client_socket):
# nothing relevant for the Q
self.received_messages = Queue.Queue()
现在,您需要为main窗口
提供一种访问所接收消息的方法。如果需要,您可以让它通过查询队列直接获取消息,但我更喜欢这样:
# Within the SockHandler Class
def get_next_message():
try:
return self.received_messages.get(True, 5)
except:
return None
无论是SockHandler
还是MainWindow
在此方法中处理超时异常。这取决于你