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

Kent Johnson kent37 at tds.net
Mon Feb 13 18:34:13 CET 2006


Kenny Li wrote:
> Kent:
>  
> I forgot to mention that no coping is allowed. Your two options 
> essentially are doing copying of the b.

Not really. I make new references to the attributes of b.

It sounds like you want
   c = C(b)
to actually convert b to be an instance of C, instead of creating a new 
object. Is that right? You can do that it C.__new__ but I wonder why you 
want to?

Here is some code that might do what you want:

''' Construction of a derived class from a base class returns the base class
     converted to an instance of the derived class '''

class B(object):
     ''' the baseClass '''
     def __init__(self, arg1, arg2):
         self.a1=arg1
         self.a2=arg2

     def __repr__(self):
         return 'B(%r, %r)' % (self.a1, self.a2)

class C(B):
     ''' C is subClass of B '''
     def __new__(cls, arg1, arg2=None):
         if isinstance(arg1, B):
             # If given a B instance, convert it to a C and return it
             arg1.__class__ = C
             return arg1

         return B.__new__(cls, arg1, arg2)

     def __init__(self, arg1, arg2=None):
         if not isinstance(arg1, B):
             B.__init__(self, arg1, arg2)
         self.extra="blah blah blah"

     def __repr__(self):
         return 'C(%r, %r, %r)' % (self.a1, self.a2, self.extra)


b=B(1, 2)
print b

c=C(2, 3)
print c

c=C(b)
print c, (c is b)
print b # b is now a C - it's the same object as c


Kent



More information about the Tutor mailing list