Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python类之间的双向通信(已编辑并添加代码)_Python_Oop_Logic - Fatal编程技术网

python类之间的双向通信(已编辑并添加代码)

python类之间的双向通信(已编辑并添加代码),python,oop,logic,Python,Oop,Logic,所以,我有需要相互交流的课程。例如,我构建了聊天程序的客户端。一个类处理套接字,另一个类处理GUI。因此GUI类必须从socket类获取接收到的数据,此外还必须通过socket类发送消息 问题是,如果让一个类包含另一个类,则无法进行双向通信。您需要将父实例传递给子实例,但我认为传递该实例不是正确的方法 最好的办法是什么 这里有一些代码,例如,希望它清楚(请阅读代码中的注释以便更好地理解): 为什么不将SockHandler实例化为main窗口的属性呢 像这样: class MainWindow:

所以,我有需要相互交流的课程。例如,我构建了聊天程序的客户端。一个类处理套接字,另一个类处理GUI。因此GUI类必须从socket类获取接收到的数据,此外还必须通过socket类发送消息

问题是,如果让一个类包含另一个类,则无法进行双向通信。您需要将父实例传递给子实例,但我认为传递该实例不是正确的方法

最好的办法是什么

这里有一些代码,例如,希望它清楚(请阅读代码中的注释以便更好地理解):


为什么不将
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
在此方法中处理超时异常。这取决于你