File: class/Workbook/Exercises/Lab6/ex3.txt

% cat mysub.py 

from mylist import MyList

class MyListSub(MyList):
    calls = 0                                     # shared by instances

    def __init__(self, start):
        self.adds = 0                             # varies in each instance
        MyList.__init__(self, start)

    def __add__(self, other):
        MyListSub.calls = MyListSub.calls + 1     # class-wide counter
        self.adds = self.adds + 1                 # per instance counts
        return MyList.__add__(self, other)

    def stats(self):
        return self.calls, self.adds         # all adds, my adds

if __name__ == '__main__':
    x = MyListSub('spam')
    y = MyListSub('foo')
    print x[2]
    print x[1:]
    print x + ['eggs']
    print x + ['toast']
    print y + ['bar']
    print x.stats()

% python mysub.py
a
['p', 'a', 'm']
['s', 'p', 'a', 'm', 'eggs']
['s', 'p', 'a', 'm', 'toast']
['f', 'o', 'o', 'bar']
(3, 2)



[Home page] Books Code Blog Python Author Train Find ©M.Lutz