runtime inheritance (e.g. __new__, __metaclass__)

Peter Otten __peter__ at web.de
Wed Jul 28 14:38:26 CEST 2004


H Jansen wrote:

> I try to work out how to use __new__ and metaclass (or __metaclass__)
> mechanisms in order to change the base class at runtime. I haven't been
> successful so far, however, even after also reading most of the relevant
> documentation.
> 
> The most simple representation (an oversimplification indeed) of what
> I'm trying to accomplish is this:
> 
> class Base1:
>      pass
> 
> class Base2:
>      pass
> 
> class Meta:
>      pass
> 
> class Good(Meta):
>      pass
> 
> What I want to achieve at runtime is this:
> 
> g1 = Good(Base1)  # a Good object with base class Base1
> g2 = Good(Base2)  # a Good object with base class Base2
> 
> Of course, this oversimplified (pseudo-code) example will not work but
> illustrates most clearly my idea. How can I come closest to realizing
> this by using the above mechanisms?

>>> class Base1: pass
...
>>> class Base2: pass
...
>>> def Good(base):
...     class Derived(base):
...             pass
...     return Derived()
...
>>> g1 = Good(Base1)
>>> g2 = Good(Base2)
>>> isinstance(g1, Base1)
True
>>> isinstance(g1, Base2)
False
>>> isinstance(g2, Base1)
False
>>> isinstance(g2, Base2)
True

:-)

Seriously, either too much information was lost in the simplification
process or you want to have instances of the same class with different
bases - which doesn't seem possible to me as the __bases__ attribute is in
the class, not the instance. On the other hand, changing base classes at
runtime is as simple as assigning __bases__. 
__new__() can serve as a factory that returns objects of an arbitrary type,
but I don't consider that good style. Metaclasses - no idea where they
could enter the picture. 


Peter




More information about the Python-list mailing list