Variable 'superclass'es?

Gordon McMillan gmcm at hypernet.com
Thu May 6 23:30:05 EDT 1999


Zigron writes:

> I think the word is 'superclass'..hm. Anyways.
> 
> What I want is a class, that inherits from a variable class.
> 
> For instance:
> 
> _Parent = ParentClass1
> 
> class FirstParent:
>     ...
> 
> class SecondParent:
>     ...
> 
> class Child(_Parent):
>     ...
> 
> class Invoker:
>     def __init__(self):
>         if expression = 1:
>             _Parent = SecondParent
>         kid = Child()
> 
> ---------
>     Seeeeee what i'm trying to do? Can it be done?

Sure can, but not quite like that. The problem is that when the 
"class Child..." statement is hit, _Parent is FirstParent. 
Reassigning to _Parent doesn't work, because the "class" statement 
has already been executed.

Under 1.5.1 and prior, you would have to use some obtuse hackery to 
get this to work, (like the metaclass hook, or building the class def 
in a string, and eval-ing it...).

Under 1.5.2, it's a piece of cake.

c = Child()
c.__class__.__bases__ = (SecondParent,)

Voila.

- Gordon




More information about the Python-list mailing list