为什么这个python代码有语法错误?

2024-10-01 10:17:46 发布

您现在位置:Python中文网/ 问答频道 /正文

为了练习python,我为树结构创建了一个简单的类,其中每个节点可以有无限个子节点。在

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)

但是,我在def print(self):行中有一个语法错误。错误在哪里?我已经寻找了很长时间,这似乎是定义python函数的正确方法。在

我也试过了

^{pr2}$

无济于事。在


Tags: inselfchildforindex节点defval
3条回答

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

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

在Python2.7(可能还有其他版本)中,可以用print函数重写print语句,然后再重写该函数。在

要做到这一点,你必须加上

from __future__ import print_function

作为文件的第一行。在

相关问题 更多 >