Python leave()只需1个参数(给定0)

时间:2011-12-18 22:53:07

标签: python class methods python-3.x self

好吧我的问题是,当从外部(顶层)调用我的类内部的方法时,它会将self参数视为它想要一个值的参数,我的类:

class Client:
    def __init__(self, host='localhost', port=5000):
        try:
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server_socket.connect((host, port))
            info.set("Connected...")
            self.boool = True
            self.gotten = ""
            self.data = ""
            b1.config(state=NORMAL)
            b2.config(state=NORMAL)
            textEntry.config(state=NORMAL)
            time.sleep(1)
            threading.Timer(1.0, self.listen).start()
        except socket.error as error:
            self.boool = False
            info.set(str(error)[14:])
        except:
            self.boool = False
            info.set("An unknown error occured")


    def leave(self):
        self.boool = False
        self.server_socket.close()
        b1.config(state=DISABLED)
        b2.config(state=DISABLED)
        textEntry.config(state=DISABLED)

    def listen(self):       
        while self.boool == True:
            time.sleep(0.1)
            self.data = self.server_socket.recv(512)
            if self.data == bytes('quit', 'UTF-8'):
                self.leave()
                print("Server has left the chat")
            elif self.data != self.gotten:
                v.set("Server: %s\n%s" % (self.data, v.get()))
                self.gotten = self.data


    def send(self, message=''):
        self.data.send(bytes(message, 'UTF-8'))
        v.set("Client: %s\n%s" % (message, v.get()))

我的调用Client类的tkinter按钮和调用方法的调用按钮leave():

b2 = Button(root, text="Leave", width=8, state=DISABLED, command=Client.leave)
b2.grid(row=0, column=3)
Button(root, text="Connect", width=8, command=Client).grid(row=0, column=4)

错误:

Traceback (most recent call last):
File "C:\Python32\chatClient2.py", line 68, in <module>
b2 = Button(root, text="Leave", width=8, state=DISABLED, command=Client.leave)
TypeError: leave() takes exactly 1 argument (0 given)

1 个答案:

答案 0 :(得分:3)

当用户按下“连接”按钮时,应该创建客户端实例,因此让它调用方法GUI.connect,创建self.client=Client()

然后使用第二种方法GUI.leave,在调用时,委托给self.client.leave()

class GUI():
    def __init__(self):
        self.client = None
    def setup_buttons(self):
        self.b1 = ...
        self.b2 = Button(root, text = "Leave", width = 8, state = DISABLED, command = self.leave)
        b2.grid(row = 0, column = 3)
        Button(root, text = "Connect", width = 8, command = self.connect).grid(row = 0, column = 4)
    def connect(self):
        self.b1.config(state = NORMAL)
        self.b2.config(state = NORMAL)
        self.client = Client()
    def leave(self):
        if self.client:
            self.b1.config(state = DISABLED)
            self.b2.config(state = DISABLED)
            self.client.leave()