call a new method of inherited class from sorted list in python

187 Views Asked by At

I made a new class inherited from list. And I have a new method of mysum(). Could you help me to call mysum() after sorting a list like this?

class MyList(list):
    def mysum(self):
        sum = 0
        for i, e in enumerate(self):
            sum += i*e
        return sum
    
    def sort(self):
        self.sort()             # ??
        return self             # ??

if __name__ == "__main__":
    ml = MyList([5, 3, 4, 1])
    print(ml.mysum())           # 1*3 + 2*4 + 3*1, OK
    print(ml.sort().mysum())    # 1*3 + 2*4 + 3*5, Doesn't work with RecursionError:
2

There are 2 best solutions below

0
flakes On BEST ANSWER

You need to call the super method. What you've done is make a recursive call (it's calling the same sort method over and over again).

class MyList(list):
    def mysum(self):
        return sum(i*e for i, e in enumerate(self))

    def sort(self):
        super().sort()
        return self

Apart from that, this doesn't seems like a good use of inheritance. If you want to work with many types of iterables, then this will become difficult. I'd define mysum as a function, and then use the standard sort methods:

def mysum(data):
    return sum(i*e for i, e in enumerate(data))


if __name__ == "__main__":
    ml = [5, 3, 4, 1]
    print(mysum(ml))
    print(mysum(sorted(ml)))
1
Joran Beasley On

change it to

def sort(self):
    super().sort()             
    return self        

this will avoid the recursion