Class hierarchy problem

Peter Otten __peter__ at web.de
Tue Aug 6 05:34:58 EDT 2013


BrJohan wrote:

> I'm in need of help to solve this Python (ver. 3.3) problem:
> 
> I have a hierarchy of classes (SubA, SubAB, SubB, ..., SubBCA,
> SubC,...), each of which is inheriting from a chain of superclasses with
> a common baseclass(Sup) on top. (So far, no problem)
> 
> Now, I want to create instances of the correct subclasstype as decided
> by the common baseclass, like this:
> 
> i = Sup(args_allowing_the_baseclass_to_deduce_correct_subclass)
> 
> where i can be of any class except Sup itself (as decided by Sup)
> 
> Now, the problem:
> 
> How to design the __new__() and __init__() methods for the various
> classes in order to achieve what I want?
> 
> (Some ten years I had the same problem (in a different context) and was
> helped by asking in this group. However, the solution has disappeared.
> Maybe the 2.x solution is not the same as in 3.x?)

Keep it simple, use a function:

def make(*args):
    class_ = deduce_correct_class(*args)
    return class_(*args)

That way you won't even need any __new__() methods.




More information about the Python-list mailing list