gpt4 book ai didi

python - 更改套接字对象的 __class__ 属性时出现类型错误

转载 作者:行者123 更新时间:2023-12-01 02:48:49 26 4
gpt4 key购买 nike

有以下服务器代码(我正在定义一个继承自套接字的类,并尝试使用该类调用客户端套接字上的发送方法):

import socket

class LogSocket(socket.socket):
def send(self, data):
print("Sending {0} to {1}".format(
data, self.getpeername()[0]))
super().send(data)

def respond(client):
response = input("Enter a value: ")
client.send(bytes(response, 'utf8'))
client.close()

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('',2401))
server.listen(1)
try:
while True:
client, addr = server.accept()
client.__class__ = LogSocket
respond(client)
finally:
server.close()

客户端代码是:

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 2401))
print("Received: {0}".format(client.recv(1024)))
client.close()

当我运行上面的代码时,服务器崩溃并出现错误:

Traceback (most recent call last):
File "10_04_server.py", line 20, in <module>
client.__class__ = LogSocket
TypeError: __class__ assignment: 'LogSocket' object layout differs from 'socket'

这个错误是什么意思?为什么会发生这种情况?

最佳答案

__slots__ 属性设置为 (),这样就可以工作:

class LogSocket(socket.socket):
__slots__ = ()
def send(self, data):
print("Sending {0} to {1}".format(
data, self.getpeername()[0]))
super().send(data)

relevant pieces of documentation是:

The action of a __slots__ declaration is limited to the class where it is defined. As a result, subclasses will have a __dict__ unless they also define __slots__ (which must only contain names of any additional slots).

还有

__class__ assignment works only if both classes have the same __slots__.

关于python - 更改套接字对象的 __class__ 属性时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45014196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com