faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 2 people (100%) answered Yes
Recently 1 of 1 people (100%) answered Yes

Entry

Variable superclasses?

Jul 5th, 2000 10:00
Nathan Wallace, Hans Nowak, Snippet 146, Gordon McMillan


"""
Packages: oop
"""
"""
> I think the word is 'superclass'..hm. Anyways.
> 
> What I want is a class, that inherits from a variable class.
> 
> For instance:
"""
class ParentClass1: pass
_Parent = ParentClass1
class FirstParent:
    pass
class SecondParent:
    pass
class Child(_Parent):
    pass
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
"""