无法重载python socket.send

时间:2010-05-14 09:21:22

标签: python inheritance overloading

我们可以看到,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 个答案:

答案 0 :(得分: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