[Tutor] Operator Overloading

Kevin Reeder reederk at comcast.net
Mon Apr 4 07:31:23 CEST 2005


Following an example from a book, I'm getting an unexpected outcome.
The point of exercise is to extend operator overloading methods from
a superclass and track the method calls. Here's the code,

class MyList:
    def __init__(self, start):
        self.wrapped = [ ]
        for x in start: self.wrapped.append(x)

    def __add__(self, other):
        return MyList(self.wrapped + other)

    def __len__(self):
        return len(self.wrapped)

=====

from module import MyList

class MyListSub(MyList):

    calls = 0

    def __init__(self, start):
        self.adds = 0
        MyList.__init__(self, start)
        
    def __add__(self, other):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1
        return MyList.__add__(self, other)

    def __len__(self):
        MyListSub.calls = MyListSub.calls + 1
        self.adds = self.adds + 1        
        return MyList.__len__(self)

    def stats(self):
        return self.calls, self.adds

This is not my code but is taken from the book I'm working with. My
problem is that whenever I call to the __add__ method the counters
increase by 2 while calls the __len__ method increase the counters
by 1 as expected. What I've concluded is that the method which
overloads and arithmetic operations executes the counter statements
twice while the method which overloads a sequencing operation
executes the counter statements only once. Otherwise, I can see no
difference between the two methods.

Here's an example,

>>> A = MyListSub([1, 2, 3])
>>> A.stats()
(0, 0)
>>> len(A)
3
>>> A.stats()
(1, 1)
>>> A + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> A.stats()
(3, 3)

I'm stumped and and would appreciate any help.

Kevin




More information about the Tutor mailing list