creating an object from base class

Ian Clark turbana at gmail.com
Fri Apr 27 23:25:54 CEST 2007


Quote iogilvy:
> i wish to have some extended functionality added to sockets
>
> i can create my own socket class   class mysocket(socket.socket):
>
> and all should be fine. Except, the sockets are created for me by the
> accept method, listening on port. So how can i take the standard
> socket created for me and create a 'mysocket'. I need a method that
> will initialise any new properties i have added in my class, but how
> can i change the class of the socket created?
>

Someone correct me if I'm wrong, but I don't believe it's possible to
change the type of objects made from builtin classes. Though if it's a
custom class you can, for example:

>>> class Foo: pass
>>> class Bar: pass
>>> obj = Foo()
>>> obj.__class__ = Bar


One option is to make your custom socket a wrapper around
socket.socket and then pass through the calls you don't want to handle
to socket.socket. The downside to this is there are quite a lot of
methods that need to be accounted for. For example:

>>> class CustomSocket:
>>>     def __init__(self, socket):
>>>         self.socket = socket
>>>     def connect(self, address):
>>>         self.socket.connect( address + '.some.tld' )
>>>     [etc]
>>>
>>> ...
>>>
>>> s = server_socket.accept()
>>> s = CustomSocket(s)


Another approach you might want to look at is populating your object
at runtime through a function. This won't give it the type you want,
but it will give it any methods and attributes it would have gotten
from your class with the added benefit of it still being of type
socket.socket. Example:

>>> def modify_socket( socket ):
>>>     socket.cabbages = 'Yuk'
>>>     socket.apples = 'Yum'
>>>
>>>     def info():
>>>         print 'Cabbages? %s\nApples? %s' % (socket.cabbages, socket.apples)
>>>     obj.show_info = info
>>>
>>> ...
>>>
>>> s = server_socket.accept()
>>> modify_socket( s )
>>> s.show_info()
Cabbages? Yuk
Apples? Yum
>>> s.apples = 'Yummie'
>>> s.show_info()
Cabbages? Yuk
Apples? Yummie
>>> type(s)
<class 'socket._socketobject'>

Good luck.

Ian



More information about the Python-list mailing list