我正在用python创建一个棋盘游戏,要求我发送由自定义Hex()类(它是元组的子类)创建的对象。我面临的问题是,当服务器收到腌制的消息(包含字符串和十六进制对象的元组)时,它将引发以下错误:
TypeError:__new __()缺少2个必需的位置参数:“ r”和“ s”
我对OOP还是比较陌生,但是我认为服务器在对元组消息进行拆包时会尝试创建Hex对象,但是显然它没有必要的信息来重新创建原始对象,因为所有对象都已打包在对象本身中。
如果有人可以提出一种方法,我可以成功地将Hex对象从客户端发送到服务器,然后再发送回给我们,则将非常感谢。
以下代码:
server.py
import socket
import pickle
HOST = '127.0.0.1'
PORT = 57343
SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
SOCK.bind((HOST, PORT))
SOCK.listen()
print('Server active, waiting for connections...')
conn, addr = SOCK.accept()
print('Connected to:', addr)
conn.send(pickle.dumps('conn test'))
print('test message sent to', conn)
while True:
try:
print('waiting for data')
data = pickle.loads(conn.recv(2048))
command, info = data
if command == 'move':
print('Received message', data)
elif command == 'get':
pass
conn.sendall(pickle.dumps('game'))
except (EOFError, ConnectionResetError) as err:
print(err)
break
print('Lost connection')
conn.close()
client.py
import tmp_hex_lib as hl
from network import Network
def main():
game_over = False
moves = []
attack_switch = False
net = Network()
net.get_player()
while not game_over: # main game loop
try:
net.send(('get', None))
except:
game_over = True
print("Couldn't find game")
break
selected_hex = hl.Hex(-13, 10, 3)
print('selected_hex has type:', type(selected_hex))
moves.append(selected_hex)
if attack_switch:
net.send(('attack', None))
else:
net.send(('move', 'this message works'))
net.send(('move', selected_hex)) # if any other type is sent, game runs fine
attack_switch = False
if __name__ == '__main__':
main()
network.py
import socket
import pickle
class Network:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = "127.0.0.1"
self.port = 57343
self.addr = (self.server, self.port)
self.player = self.connect()
def get_player(self):
return self.player
def connect(self):
try:
self.client.connect(self.addr)
print('connecting to server')
data = pickle.loads(self.client.recv(2048))
print('Received data:', data)
return data
except EOFError as err:
print(err)
def send(self, data):
try:
self.client.send(pickle.dumps(data))
return pickle.loads(self.client.recv(2048))
except socket.error as err:
print(err)
tmp_hex_lib.py
class Hex(tuple):
def __new__(self, q, r, s):
return tuple.__new__(self, (q, r, s))
def __init__(self, q, r, s):
self.q = q
self.r = r
self.s = s
assert not (round(q + r + s) != 0), "q + r + s must be 0"
答案 0 :(得分:1)
因此,在查阅泡菜文档之后,我发现了有关泡菜类实例的文章。看来,如果要定义自己的__new__()
方法,则还必须定义一个方法__getnewargs__(self)
,该方法将__new__()
所需的所有变量返回为元组。例如(无双关语),我的情况是:
tmp_hex_lib.py
class Hex(tuple):
def __new__(self, q, r, s):
return tuple.__new__(self, (q, r, s))
def __getnewargs__(self):
return self.q self.r, self.s
def __init__(self, q, r, s):
self.q = q
self.r = r
self.s = s
assert not (round(q + r + s) != 0), "q + r + s must be 0"
希望这对其他人有帮助!