Recursive class | can you modify self directly?

Russel Walker russ.pobox at gmail.com
Thu Jul 11 00:50:50 CEST 2013


I've been mucking around with this silly class pretty much the whole day and my eyes are about closing now so this is the solution for now I think. Please feel free to drop any suggestions. I think I mostly just ended up shaving off allot of extraneous responsibility for the class, that and inheriting from list. I wanted to try it and it seems to fit (I think).

Maybe tomorrow I'll try it inheriting from instead since that is immutable. Should've probably thought of that before right this moment, as I had quite a time with "maximum recursion depth exceeded".


class LRExpression(list):
    """
    Construct for 'left to right' algebraic expressions.
    """

    def __init__(self, *args):
        list.__init__(self, args[:1])
        for x in args[1:]:
            self.append(x)

    def __str__(self):
        return '(%s)' % ' '.join(map(str, self))

    def evaluate(self):
        return eval(str(self))

    def append(self, x):
        if len(self) < 3:
            list.append(self, x)
        else:
            oldself = LRExpression(*self)
            self.__init__(oldself)
            self.append(x)


def test():
    a = LRExpression(1)
    a.append('+')
    a.append(2)
    a.append('*')
    a.append(3)
    try:
        print 'repr:', repr(a)
        print 'str:', a
        print "should be 9:", a.evaluate()
    except Exception as er:
        print er




More information about the Python-list mailing list