Inheritance question

Peter Otten __peter__ at web.de
Mon Sep 20 16:24:58 CEST 2004


Yannick Turgeon wrote:

> is there a way that I could change my class A to something like:
> 
> class A:
>     _value
>     __init__(self, value):
>         self._value = value
>         if value > 10:
>             set myself as an instance of B1   # How can I do that?
>         else:
>             set myself as an instance of B2
> 
> in the real situation "value" is encoded and the way to know what kind of
> A it is, is more complex than just look at the value.

[Requires newstyle classes]

>>> class A(object):
...     def __new__(cls, value):
...             if value > 10:
...                     return super(cls, A).__new__(B1, value)
...             else:
...                     return super(cls, A).__new__(B2, value)
...     def __init__(self, value):
...             self._value = value
...
>>> class B1(A):
...     def doPrint(self):
...             print "B1:", self._value
...
>>> class B2(A):
...     def doPrint(self):
...             print "B2:", self._value
...
>>> A(1).doPrint()
B2: 1
>>> A(100).doPrint()
B1: 100

You can do it, but it's certainly bad design because A has to know all its
subclasses. If you go with the above I recommend that you use some kind of
registry instead of hardcoding the subclasses in A.__new__().

Peter




More information about the Python-list mailing list