Newbie inheritance problem

zzzzz zzizz_ at notmail.com
Mon Apr 2 19:46:23 EDT 2001


Thanks all,

>        return self.__class__(self._value+other._value)
Seems to do exactly what I want, PS let me apologize for the lack of
:'s on my methods that I posted.


On Mon, 2 Apr 2001 14:51:22 +0200, "Alex Martelli" <aleaxit at yahoo.com>
wrote:

>"zzzzz" <zzizz_ at notmail.com> wrote in message
>news:17ogct0jjvuhnb8g8ji9uqh011egdn0l2b at 4ax.com...
>> Hi all, I have overwridden the __add__ method for a class, then built
>> a class based on the above class; however, the object I'm returning is
>> of the base class not the inherited class. If that doesn't make sense
>> see below:
>>
>> class A:
>>     def __init__(self,value=0.0)
>>         self._value=float(value)
>>     def __add__(self,other)
>>         return A(self._value+other._value)
>>
>> class B(A):
>>     pass
>>
>> x=B(3)
>> y=B(2)
>> z=x+y
>>
>> The way I've done it z becomes an instance of A not B!!! How do I do
>
>Right, it does -- it is constructed (by A's method __add__) with
>a hardwired 'A'.
>
>
>> it correctly? Do I have to override all the __add__, __sub__, etc...
>> methods?
>
>If I understand your desire correctly, changing the definition of
>A's method __add__ to:
>
>    def __add__(self,other)
>        return self.__class__(self._value+other._value)
>
>might accomplish a part of it.  Of course, this may not be quite
>enough -- what if the LH operand is an A but the RH one is a B,
>for example -- choosing what class to use to generate the needed
>result may be very complex, but I hope this gets you started.
>
>
>Alex
>
>

Regards,

zzzzz.
---------------------



More information about the Python-list mailing list