[Tutor] Fwd: Instantiate a subClass using an instance of its baseClass
Kenny Li
kenny.li at gmail.com
Mon Feb 13 18:04:29 CET 2006
Kent:
I forgot to mention that no coping is allowed. Your two options essentially
are doing copying of the b.
Furthermore, let's say, I don't even know the inside details of B, for
example, I subclass the socket.socket,
and I got a client socket after it accepting an incoming connection, and I
want to use the newly gotten client
socket to create an instance of the subClass. Following is the way normally
I would do,
but I don't know the abnormal case---gotten an client socket (instance of
socket.socket) and trying to use it
to create an instance of MySocket (subclass of socket.socket).
import socket
class MySocket(socket.socket):
''' my special socket '''
def __init__(self, family, sock_type):
socket.socket.__init__(self, family, socket_type)
self.extra="blah blah blah"
Hope this help clarifying my intent.
On 2/13/06, Kent Johnson <kent37 at tds.net> wrote:
>
> Kenny Li wrote:
> > *class B(object): *
> > * ''' the baseClass '''*
> > * def __init__(self, arg1, arg2):*
> > * self.a1=arg1*
> > * self.a2=arg2*
> > * *
> > *class C(B): *
> > * ''' C is subClass of B '''*
> > * def __init__(self, arg1, arg2):*
> > * B.__init__(self, arg1, arg2)*
> > * self.extra="blah blah blah"*
> > **
> > *if __name__ == '__main__':*
> > * # Now, I ran into a situation, where I don't have the values
> > of "arg1 and arg2", *
> > * # but I do have an instance of baseClass (B), called b. *
> > **
> > * # How do I write the class C [for example, its
> > __new__(cls...) static method] to enable me to do the following?*
> > * c=C(b) # <<< This is what I want.*
>
> Two options:
>
> 1. Just pass b.a1 and b.a2 to the C constructor:
> c = C(b.a1, b.a2)
>
> A little clumsy but it works.
>
> 2. Write C.__init__() to accept either form:
> def __init__(self, arg1, arg2=None):
> if isinstance(arg1, B):
> arg1, arg2 = arg1.a1, arg1.a2
> # the rest as before
>
> Kent
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060213/85b175be/attachment.html
More information about the Tutor
mailing list