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

Kent Johnson kent37 at tds.net
Mon Feb 13 11:59:15 CET 2006


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



More information about the Tutor mailing list