Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing and built-in methods in Python

For convenience, I wanted to subclass socket to create an ICMP socket:

class ICMPSocket(socket.socket):
    def __init__(self):
        socket.socket.__init__(
            self, 
            socket.AF_INET,
            socket.SOCK_RAW,
            socket.getprotobyname("icmp"))

    def sendto(self, data, host):
        socket.socket.sendto(self, data, (host, 1))

However, I can't override socket.sendto:

>>> s = icmp.ICMPSocket()
>>> s.sendto
<built-in method sendto of _socket.socket object at 0x100587f00>

This is because sendto is a "built-in method". According to the data model reference, this is "really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument."

My question: is there anyway to override built-in methods when subclassing?

[Edit] Second question: if not, why not?

like image 351
grifaton Avatar asked Aug 07 '11 22:08

grifaton


1 Answers

I know this doesn't answer your question, but you could put the socket into an instance variable. This is what Nobody also suggested in the comments.

class ICMPSocket():
    def __init__(self):
        self.s = socket.socket(
            socket.AF_INET,
            socket.SOCK_RAW,
            socket.getprotobyname("icmp"))
    def sendto(self, data, host):
        self.s.sendto(data, (host, 1))
    def __getattr__(self, attr):
        return getattr(self.s, attr)
like image 160
Karoly Horvath Avatar answered Oct 17 '22 19:10

Karoly Horvath