Python 类型错误:__init__() 缺少 2 个必需的位置参数:“client_socket”和“statusMessage”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28122963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: __init__() missing 2 required positional arguments: 'client_socket' and 'statusMessage'
提问by ssd20072
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 {}\n'.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'
采纳答案by GLHF
class SimpleClient:
def __init__(self, client_socket, statusMessage):
Your class taking two arguments, but when you call it;
你的类有两个参数,但是当你调用它时;
client = SimpleClient()
You didn't write any arguments. So you have to put 2 arguments they may be None
.
你没有写任何参数。因此,您必须输入 2 个参数,它们可能是None
.
回答by ronakg
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).
如果您想允许不向类启动器传递任何参数,则必须使用设置为None
(或任何合适的)的默认值来定义启动器。
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()