A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-list/2001-April/084186.html below:

Newbie inheritance problem

Newbie inheritance problemMichael Hudson mwh21 at cam.ac.uk
Mon Apr 2 08:57:06 EDT 2001
zzzzz <zzizz_ at notmail.com> writes:

> 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
> it correctly? Do I have to override all the __add__, __sub__, etc...
> methods?

Well, you can do this:

class A:
    def  __init__(self,value=0.0)
        self._value=float(value)
    def __add__(self,other)
        return self.__class__(self._value+other._value)

HTH,
M.

-- 
  same software, different verbosity settings (this one goes to
  eleven)                             -- the effbot on the martellibot

More information about the Python-list mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4