Reputation: 1436
I'm trying to override a python class (first time doing this), and I can't seem to override this method. When I run this, my recv method doesn't run. It runs the superclasses's method instead. What am I doing wrong here? (This is python 2.7 by the way.)
import socket
class PersistentSocket(socket.socket):
def recv(self, count):
print("test")
return super(self.__class__, self).recv(count)
if __name__ == '__main__':
s = PersistentSocket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 2300))
print(s.recv(1)
Upvotes: 4
Views: 2008
Reputation: 2855
Picking on the explanation from @user2357112, one thing that seems to have helped is to do a delattr(self, 'recv')
on the class constructor (inheriting from socket.SocketType
) and then define you own recv
method; for example:
class PersistentSocket(socket.SocketType):
def __init__(self):
"""As usual."""
delattr(self, 'recv')
def recv(self, buffersize=1024, flags=0):
"""Your own implementation here."""
return None
Upvotes: 0
Reputation: 280335
The socket type (officially socket.SocketType
, though socket.socket
happens to be the same object) makes the strange choice of implementing recv
and a few other methods as instance attributes, rather than as normal methods in the class dict. In socket.SocketType.__init__
, it sets a self.recv
instance attribute that overrides the recv
method you tried to define.
Upvotes: 5