Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 662
Luka Rahne Avatar asked May 14 '10 09:05

Luka Rahne


1 Answers

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
like image 57
kmerenkov Avatar answered Oct 03 '22 05:10

kmerenkov