Subclasses 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 cannot 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 “a really nice disguise of an inline function, this time containing an object passed to C as an implicit optional argument.”

My question is: is there a way to override inline methods when subclassing?

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

+6
source share
2 answers

I know this does not answer your question, but you can put the socket in an instance variable. This is what no one 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) 
+6
source

Re-editing . My first solution did not work, and after some break with this, I can conclude that in the case of a python socket, when you can say that aggregation is much better than inheritance, but if you want to know how you can do it it uses inheritance check this code:

 import socket class ICMPSocket(socket.socket): def __init__(self): self._sock = socket.socket( socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")) # Delete the methods overrited by the socket initializer to make # possible defining our own. for attr in socket._delegate_methods: try: delattr(self, attr) except AttributeError: pass def sendto(self, data, flags, addr): return self._sock.sendto(data, flags, (addr, 1)) icmp = ICMPSocket() print icmp.sendto('PING', 0, '127.0.0.1') 
+4
source

Source: https://habr.com/ru/post/894498/


All Articles