无法重载python socket.send

5 投票
1 回答
2309 浏览
提问于 2025-04-15 22:42

从上面的内容可以看出,send方法并没有被重载。

from socket import socket

class PolySocket(socket):

    def __init__(self,*p):
        print "PolySocket init"
        socket.__init__(self,*p)

    def sendall(self,*p):
        print "PolySocket sendall"
        return socket.sendall(self,*p)

    def send(self,*p):
        print "PolySocket send"
        return socket.send(self,*p)


    def connect(self,*p):
        print "connecting..."
        socket.connect(self,*p)
        print "connected"

HOST="stackoverflow.com"   
PORT=80
readbuffer=""

s=PolySocket()
s.connect((HOST, PORT))
s.send("a")
s.sendall("a")

输出结果:

PolySocket init
connecting...
connected
PolySocket sendall

1 个回答

9

我相信你其实并不需要这个,还有其他方法可以解决你的问题(不是通过子类化,而是直接解决实际任务)。

如果你真的需要模拟一个对象,可以使用代理对象:

from socket import socket


class PolySocket(object):
    def __init__(self, *p):
        print "PolySocket init"
        self._sock = socket(*p)

    def __getattr__(self, name):
        return getattr(self._sock, name)

    def sendall(self, *p):
        print "PolySocket sendall"
        return self._sock.sendall(*p)

    def send(self, *p):
        print "PolySocket send"
        return self._sock.send(*p)

    def connect(self, *p):
        print "connecting..."
        self._sock.connect(*p)
        print "connected"

HOST = "stackoverflow.com"
PORT = 80
readbuffer = ""

s = PolySocket()
s.connect((HOST, PORT))
s.send("a")
s.sendall("a")

这是输出结果:

% python foo.py
PolySocket init
connecting...
connected
PolySocket send
PolySocket sendall

撰写回答