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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With