converting base class instance to derived class instance

Peter Otten __peter__ at web.de
Tue Jan 20 13:53:06 CET 2004


Sridhar R wrote:

> Consider the code below,
> 
> class Base(object):
>   pass
> 
> class Derived(object):

I suppose that should be 

  class Derived(Base):
> 
>   def __new__(cls, *args, **kwds):
>     # some_factory returns an instance of Base
>     # and I have to derive from this instance!
>     inst = some_factory() # this returns instance of Base
      
      # using brute force: 
      inst.__class__ = Derived

No guarantees, but the above seems to work.
      
>     return inst  # Oops! this isn't an instance of Derived
> 
>   def __init__(self):
>     # This won't be called as __new__ returns Base's instance
>     pass
> 
>   The constrait is there is some factory function that creates an
> instance of Base class.  So I _can't_ call "Base.__init__(self)" in
> Derived.__init__ func, as their will be _two_ instances (one created
> by Derived.__init__ and other created by the factory function)

As some_factory() returns an already initialized instance of Base, there
should be no need to call it again from inside Derived.__init__()
 
>   Simply I want to get a derived class object, but instead of allowing
> _automatic_ creation of Base instance, I want to use _existing_ Base's
> instance, then use this as a Derived's instance.
> 
>   Will metaclass solve this problem?

I think metaclasses will solve only metaproblems...

Skeptically yours,
Peter




More information about the Python-list mailing list