2

To practice python, I made a simple class for a tree structure in which each node can have infinite child nodes.

class Tree():

  def __init__(self, children, val):
    self.children = children
    self.val = val

  def add(self, child):
    self.children.append(child)

  def remove(self, index):
    child = self.children[index]
    self.children.remove(child)
    return child

  def print(self):
    self.__print__(0)

  def __print__(self, indentation):
    valstr = ''
    for i in range(0, indentation):
      valstr += ' '
    valstr += self.val
    for child in self.children:
      child.__print__(indentation + 1)

However, I have a syntax error in the line def print(self):. Where is the error? I have been looking for a long time, and it seems like the right way to define a python function.

I have also tried

  @override
  def print(self):
    self.__print__(0)

to no avail.

4

3 回答 3

7

In Python 2 print is a keyword, so you can't use it as the name of a function or method.

于 2013-01-29T02:58:21.983 回答
3

In Python 2.7 (and maybe other versions) you can override the print statement with a print function and than override that function.

To do that you have to add

from __future__ import print_function

as the first line of your file.

于 2013-01-29T03:06:13.190 回答
2

In Python 2 print is a reserved word and cannot be the name of a variable or method or function.

于 2013-01-29T02:58:39.363 回答