Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

python - TypeError: __init__() missing 2 required positional arguments: 'client_socket' and 'statusMessage'

import socket
import sys

class SimpleClient:
    def __init__(self, client_socket, statusMessage):
        self.client_socket = client_socket
        self.statusMessage = statusMessage

    def connectToServer(self):
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        host  = 'cs5700sp15.ccs.neu.edu'
        port  = 27993

        remote_ip = socket.gethostbyname(host)

        try:
            self.client_socket.connect((remote_ip, port))
        except socket.error:
            print ('Connection failed')
            sys.exit()

        print ('Connection successful')

    def sendHelloMessage(self):
        """This funtion sends the initial HELLO message to the server"""
        nu_id = input('Enter your NUID: ')
        hello_message = 'cs5700spring2015 HELLO {}
'.format(nu_id)
        self.client_socket.send(bytes(hello_message, 'ascii'))

    def receiveStatusMessage(self):
        """This function receives the STATUS message from the server"""
        self.statusMessage = str(self.client_socket.recv(1024))
        print (self.statusMessage)

        #handleStatusMessage()

def main():
  client = SimpleClient()
  client.connectToServer()
  client.sendHelloMessage()
  client.receiveStatusMessage()  

if __name__ == "__main__":main()

I get the following error:

Traceback (most recent call last):
  File "/Users/sanketdeshpande/Documents/workspace/test/project01-simpleclient.py", line 49, in <module>
    if __name__ == "__main__":main()
  File "/Users/sanketdeshpande/Documents/workspace/test/project01-simpleclient.py", line 44, in main
    client = SimpleClient()
TypeError: __init__() missing 2 required positional arguments: 'client_socket' and 'statusMessage'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to allow passing no arguments to the Class initiator, you have to define the initiator with default values set to None (or whatever is appropriate).

For example,

def __init__(self, client_socket=None, statusMessage=""):
    self.client_socket = client_socket
    self.statusMessage = statusMessage

Now you can call your class instantiation without passing initialization parameters.

client = SimpleClient()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...