简体   繁体   中英

Why can't I override this method in python?

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)

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.

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

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