如何在两个班级之间共享数据 [英] How to share data between two classes

查看:100
本文介绍了如何在两个班级之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

有没有办法让两个类同时互相继承?

Is there a way to have two classes simultaneously inherit from one another?

背景

我目前正在研究Socket Server项目.在这个项目中,我有两个类,一个Server类和一个GUI类.他们的目的是不言自明的.但是,我显然需要使两个类相互通信.在程序中,我首先声明Socket_Server类,然后声明GUI类.

I am currently working on a Socket Server project. In this project, I have a two classes, a Server class, and a GUI class. Their purposes are self explanatory. But, I obviously need to have the two classes communicate with one another. In the program, I first declare the Socket_Server class, and then the GUI class.

我问了一个类似的问题,如何从Python方法中访问函数,但从未得到令人满意的答复.请尝试回答.

I asked a similar question, How to Access Functions from Methods in Python, which was never satisfactorily answered. Please try to answer either.

代码和错误

GUI类中,我有一个名为self.message.的文本框,用于向所有客户端发送消息.我试图通过使用以下语法来继承此类:

In the GUI class, I have a textbox called self.message. It is used to send a message to all clients. I attempted to inherit this class by using this syntax:

class Socket_Server(GUI.messageFun):

接下来,GUI类从Socket_Server继承-

Next, the GUI class inherits from the Socket_Server -

class GUI(Frame, Socket_Server): 

第二个继承GUI(Socket_Server)正常工作,但第一个继承失败.

The second inheritance GUI(Socket_Server) works correctly, but the first one fails.

按钮的命令是这个

        self.send = Button (self.messageFrame, text = "Send",
                        command = lambda: new_server.send_cmd()) 

new_serverSocket_Server类的实例.

当前错误消息是这样的:

The current Error Message is this:

Socket Created
Socket Bind Complete
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
    return self.func(*args)
  File "D:\Python Programs\Sockets\IM Project\Server\Server GUI InDev Class.py", line 129, in <lambda>
    command = lambda: new_server.send_cmd())
  File "D:\Python Programs\Sockets\IM Project\Server\Server GUI InDev Class.py", line 82, in send_cmd
    message = self.message.get("0.0",END)
AttributeError: Socket_Server instance has no attribute 'message'

推荐答案

此问题的标题与您刚开始提出的问题有所不同(并且更加准确),但都不符合您的要求.您需要传达两个不同类的实例;那不是继承.

The title of this question is different (and a bit more accurate) than the question you ask at the beginning, but none of them fit with what you want. What you need is to communicate two instances of different classes; that is not inheritance.

使用继承时,您应该问自己是否每个X也是Y:

When you use inheritance, you should ask yourself if every X is also an Y:

  • 每个EmployeePerson吗?
  • 每个PersonEmployee吗?
  • 每个EmployeeCar吗?
  • Is every Employee a Person? Yes
  • Is every Person an Employee? No
  • Is every Employee a Car? No

牢记这一概念,您可能会看到第三个示例与GUIServer之间的关系最相似.这是因为您的真正问题是:

With this concept in mind, you may see the third example is the most similar to the relation between GUI and Server. It is because your real question is:

  • GUI实例是否使用Server对象?
  • Does a GUI instance use a Server object?

如果答案为是,则服务器应为GUI类的属性.在下面的示例中,您可以看到GUI调用了Server对象的方法,但没有相反的方法:

If the answer is yes, then the server should be an attribute of your GUI class. In the following example, you can see that GUI calls methods of the Server object, but not the other way around:

import Tkinter as tk
import threading
import socket

class Server():
    def __init__(self):
        self.addresses = [('localhost', 12345)] # All addresses to send data
    def sendtoall(self, data):
        for address in self.addresses:
            self._send(address, data)
    def _send(self, address, data):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect(address)
            sock.sendall(data)
        finally:
            sock.close()

class GUI(tk.Tk):
    def __init__(self, server):
        tk.Tk.__init__(self)
        self.server = server
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Send", command= self.sendmessage)
        self.entry.pack()
        self.button.pack()
    def sendmessage(self):
        message = self.entry.get()
        threading.Thread(target=self.server.sendtoall, args=(message,)).start()

server = Server()
gui = GUI(server)
gui.mainloop()

此代码看起来更像是客户端而不是服务器,因此,最好将其重命名为与您所想到的概念类似的名称(例如,Notifier )

This code looks more like a client than a server, so it may be a good idea to rename it to something more similar to the concept you have in mind (e.g., Notifier)

这篇关于如何在两个班级之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆