更改socket obj的\uqiu class\uu属性时发生类型错误

2024-10-02 02:39:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()

客户代码是:

^{pr2}$

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

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'

这个错误是什么意思?为什么会发生?在


Tags: 代码self服务器clientsendclosedataserver
1条回答
网友
1楼 · 发布于 2024-10-02 02:39:31

__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__.

相关问题 更多 >

    热门问题