Problem with operator overloading and inheritance in Python

Edward A. Waugh edward_waugh at
Sun Sep 17 21:36:30 CEST 2006

Consider the following code:

import sys

class FirstClass:
    def __init__(self, value): = value
    def __add__(self, value):
        return FirstClass( + value)
    def display(self):

class SecondClass(FirstClass):
    def __add__(self, value):
        # Generalized version of SecondClass( + value).
        sum = FirstClass( + value
        return SecondClass(
    def display2(self):

x = SecondClass(1)
# Must reimplement __add__ in SecondClass or else x after the assignment is
# an instance of class FirstClass not SecondClass.  This implies that all
# subclasses of classes that overload operators such as + must reimplement
# those methods to ensure that the class being returned is correct.
x += 1 

Note the comments in the code and observe that as is execution yields:


But if the reimplementation of __add__ in SecondClass is removed (or commented out) then as claimed in the comment above the code does not work:

Traceback (most recent call last):
  File "C:\Files\Python\", line 25, in ?
AttributeError: FirstClass instance has no attribute 'display2'

This is because x after the statement x += 1 has been executed is an object of class FirstClass because the method implementing addition in FirstClass explicitly returns a FirstClass object.

This seems to me to be a big problem because what this means is that if class X overloads any operator, e.g. addition, then all subclass of X (and all subclasses of those subclasses recursively)
must reimplement all the operator methods defined in X.

Is this a real problem with Python or just the way I am coding it as I admit that I am new to Python?
If its my fault then what is the correct way to implement SecondClass?


P.S. Why were slices ([low:high]) implemented to return the low'th to high-1'th values of a sequence?  For example I would expect that [2:4] of "abcdef" would return "cde" not "cd" and this is the case in other languages that do support slices of strings (HP BASIC) and arrays (Perl).  But I do accept that this a personal preference of mine so if folks don't agree with me that is fine.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list