Subclassing and built-in methods in Python

白昼怎懂夜的黑 提交于 2019-12-04 05:58:31

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)

Re-edit : My first solution wasn't working, and after straggling with this for sometime , i can conclude that in the case of python socket when you can say that aggregation is much better than inheriting but in case you want to know how you can do it using 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')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!