简体   繁体   中英

Can't overload python socket.send

As we can see, send method is not overloaded.

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

Output:

PolySocket init
connecting...
connected
PolySocket sendall

I am sure you don't actually need it and there are other ways to solve your task (not subclassing but the real task).

If you really need to mock object, go with proxy object:

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

Here's the output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM