converting base class instance to derived class instance

John Roth newsgroups at jhrothjr.com
Tue Jan 20 11:31:46 EST 2004


"Sridhar R" <sridharinfinity at yahoo.com> wrote in message
news:930ba99a.0401200413.5fae6fb9 at posting.google.com...
> Consider the code below,
>
> class Base(object):
>   pass
>
> class Derived(object):
>
>   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
>     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

__new__ can return an instance of any class it pleases.
It's not restricted to returning an instance of the class it
happens to be in, nor is it restricted to returning a newly
created instance, for that matter. It can do the entire
construction job without using the __init__ method.

However, I don't think that's the best solution. If
your factory is going to return instances of several
different classes, I think it's best that it be an explicit
factory method or function, not something that magically
happens in a class constructor. I'd rather not have to
deal with programs where class constructors pass me
instances of classes other than the one I'm calling.

If you want to do a little bit of deep magic, a factory
function can create an instance by calling object(),
plug in whatever attributes it wants and then change the
__class__ attribute to whatever class it wants before
it returns the newly minted instance. It doesn't have to
go near anything that resembles a constructor (other than
calling object() to get a new instance, of course.)

>   The constraint 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)
>
>   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?

Wrong tool. Metaclasses are used to set up classes, not to
set up instances.

John Roth





More information about the Python-list mailing list