[Tutor] Instantiate a subClass using an instance of its baseClass

Kent Johnson kent37 at tds.net
Mon Feb 13 20:17:15 CET 2006


Kenny Li wrote:
> Yep! I think that is what I want. I did not know enough to do (inside 
> C.__init__() ):
>         arg1.__class__=C
>  
> As to my intent, I want to subclass socket.socket. By doing so, I may 
> get a socket (instance of my baseClass) after it (my subclass) accepts 
> an incoming connection, and I want to use the subclass instance (the 
> client socket) to get an instance of my subclass.
>  
> Do you think your solution would work in my socket.socket subclassing 
> case? (I will give it a try to verify, just asking before I even try)

I think so :-) unless some socket code is looking at the actual class of 
the socket.

But why not just override socket.accept() to do what you want? Here is 
the full def of socket.accept():

     def accept(self):
         sock, addr = self._sock.accept()
         return _socketobject(_sock=sock), addr

Just change it to

     def accept(self):
         sock, addr = self._sock.accept()
         return MySocket(_sock=sock), addr

> Again, Thanks a lot, Kent!
>  
> PS: there is information about __new__(), but there seems not a lot 
> about __class__, could you point me to some web sources about __class__?

Google "site:docs.python.org __class__" and especially
http://docs.python.org/dev/lib/specialattrs.html

Kent



More information about the Tutor mailing list