简体   繁体   中英

Why does this python code have a syntax error?

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.

在 Python 2 中print是一个关键字,因此您不能将其用作函数或方法的名称。

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.

在 Python 2 中, print是一个保留字,不能是变量、方法或函数的名称。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM