Overriding (factory?) methods and inheritance ...

Bengt Richter bokr at oz.net
Tue Dec 31 12:48:32 EST 2002


On Mon, 30 Dec 2002 16:43:35 GMT, "Rocco Rossi" <rockrossi69 at libero.it> wrote:

>I posted a message yesterday about problems I was having when inheriting
>from base classes that contained methods (would it be correct to call them
>"factory" methods) which produced instances of the same class (type), like a
>RationalNumber class or a ComplexNumber class or Vector class, and so on.
>
>The inherited specialized class would of course have those same methods
>return values of the base class type, so that in the end one would not be
>able to exploit the new features of the inherited class for those values ...
>no code re-use!!!
>
>One way out, of course, (which was also suggested by Laotseu --- BTW
>thanks ---), would be to override precisely those methods, and like I said,
>we would be losing the benefits of object-oriented programming that way, but
>it certainly still is possible to let the base class do the majority of the
>work ... Has this problem ever come up before? It seems to me that it is
>non-trivial, but then again maybe I'm not confronting it in the appropriate
>manner. Need some help.
>
IWT one could write a metaclass to automate doing something like the override
below, which uses the base class method and makes a new subclass instance from
the result. If most of the methods should be overridden, you could list the ones
to leave alone, or vice versa.

 >>> class N(int):
 ...     def __add__(self, other): return self.__class__(int.__add__(self, other))
 ...
 >>> n=N(123)
 >>> n
 123
 >>> type(n)
 <class '__main__.N'>
 >>> n = n+ 321
 >>> n
 444
 >>> type(n)
 <class '__main__.N'>

Here we didn't override __radd__, so we still get the result from the base class

 >>> 444+n
 888
 >>> type(444+n)
 <type 'int'>

Regards,
Bengt Richter



More information about the Python-list mailing list