class Sym: val = '' tag = 'sym' def __init__(self, V): self.val = V nest = [] def push(self, o): self.nest.append(o) return self def __repr__(self): return self.dump() def head(self): return "<" + self.tag + ":" + self.val + ">" def pad(self, N): return '\t' * N def dump(self, depth=0): S = "\n" + self.pad(depth) + self.head() for i in self.nest: S += i.dump(depth+1) return S print Sym('symbol').push(Sym('+')) 
  • Maybe here? for i in self.nest: S += i.dump(depth+1) . There is a search on self.nest - users
  • naturally, but I don’t see any crime, usual recursion, analogue in C ++ works without questions - Dmitry Ponyatov

1 answer 1

The problem is that the fields declared in the body of the class description are static . Those. nest [] in sym: + will also include sym: symbol, and endless recursion occurs.

Fixed:

 class Sym: #del val = '' def __init__(self, V): self.val = V; self.nest=[] #del nest = [] 
  • There are no "static" fields in Python. The terms here are: class attributes (common to all class instances) and instance attributes (each has its own). Both can be accessed using the self.nest syntax. The problem you have is that Sym.nest is an attribute of a class, not an instance. Move the attribute creation inside the method ( __init__ ). Related question: Why are the fields of two output objects mixed up? - jfs