Subclass dynamically

Carl Banks pavlovevidence at gmail.com
Sun Aug 9 01:10:20 CEST 2009


On Aug 8, 12:13 pm, Luis Alberto Zarrabeitia Gomez <ky... at uh.cu>
wrote:
> Quoting Robert Dailey <rcdai... at gmail.com>:
>
> > Hey,
>
> > I have a class that I want to have a different base class depending on
> > a parameter that I pass to its __init__method. For example
> > (pseudocode):
>
> 1- Are you sure that you want that behavior? Given that in python, a class is
> just a particular case of invocable object, you could just write a function
> instead, and the code may be more robust.
>
> 2- If you are /sure/ that is the behavior you want, take a look at the __new__
> method. The __new__ can decide which instance to return (you could even define a
> new class inside of it, instantiate it, and return the instance).
>
> 3- You may want to take a look at metaclasses. But without more details about
> why you want it, I can't give you more precise answers.

One could accomplish this using methods 2 and 3, but it would go
against so many common expectations I have to recommend never doing
it.  If you call a type, it should return an object of that type (or,
at worst, a subtype or "null" type) or raise an exception.

The factory function is the way to do this.

Another alternative is to forego inheritance and simply call method on
the passed "base" object.  Given that the OP posted code that almost
literally works in that case, this might be the best way to go for his
case.

So instead of this hypothetical code:

class MyDerived(self.base):
    def __init__(self,base)
        self.base = base
    # MyDerived inherits a_method() from self.base

He could go with this real code:

class MyClass(object):
    def __init__(self,base)
        self.base = base
    def a_method(self):
        return self.base.a_method()

where, instead of inheriting self.base's a_method, it simply defines
a_method() to call self.base.a_method() directly.


Carl Banks



More information about the Python-list mailing list