繁体   English   中英

Python:类声明中的递归

[英]Python: recursion in Class declaration

我正在尝试在 Python 的类声明中实现递归函数。 但是,该函数似乎不接受参数。 如果我在 Class 之外声明一个递归函数,它就可以工作。

[一个while循环][1]也可以解决问题。 (请参阅“遍历值”。恕我直言,我已经在键盘上敲了敲头,足以允许发布 SO 帖子。

class Node:
    def __init__(self, value):
        self.data = value
        self.next = None
    def traverse(self, node):
        print(node.data)
        if (node.next == None):
            return
        else:
            node.traverse(node.next)

            
>>> a = Node('a')
>>> b = Node('b')
>>> c = Node('c')
>>> a.next = b
>>> b.next = c
>>> Node.traverse(a)
Traceback (most recent call last):
  File "<pyshell#62>", line 1, in <module>
    Node.traverse(a)
TypeError: traverse() missing 1 required positional argument: 'node'


  [1]: https://medium.com/@kojinoshiba/data-structures-in-python-series-1-linked-lists-d9f848537b4d

一个更典型的实现是。

节点代码

class Node:
    def __init__(self, value):
        self.data = value
        self.next = None
        
    def traverse(self):               # instance method (no 2nd argument node)
        if self:                      # check if node
            print(self.data)          # output data
            if self.next:             # check for next node
                self.next.traverse()  # recursive call to next node if any
       

测试

a = Node('a')
b = Node('b')
c = Node('c')
a.next = b
b.next = c
a.traverse()     # Note: Node.traverse(a) also works
                 # This is because
                 # When you call an instance method (e.g. traverse) from an
                 # instance object (e.g. a), Python automatically passes 
                 # that instance object as the first argument (in addition
                 # to any other arguments) to the function call
                 # Thus: a.traverse() becomes Node.traverse(a)

输出

a
b
c

您需要使traverse成为类方法。 目前,它表示您缺少node参数,因为在Node.traverse(a)您提供了self=a而不是node=a

class Node:
    def __init__(self, value):
        self.data = value
        self.next = None

    @classmethod # This is the only addition needed :) 
    def traverse(self, node):
        print(node.data)
        if node.next is None:
            return
        else:
            node.traverse(node.next)

Python Cookbook ,第 117 页,你会发现这个秘诀是这个问题的更好解决方案:

class Node:
  def __init__(self, value):
    self._value = value
    self._children = []

  def __repr__(self):
    return 'Node({!r})'.format(self._value)

  def add_child(self, node):
    self._children.append(node)

  def __iter__(self):
    return iter(self._children)

  def depth_first(self):
    yield self
    for c in self:
      yield from c.depth_first()


if __name__ == '__main__':
  root = Node(0)
  child1 = Node(1)
  child2 = Node(2)
  root.add_child(child1)
  root.add_child(child2)
  child1.add_child(Node(3))
  child1.add_child(Node(4))
  child2.add_child(Node(5))
  for ch in root.depth_first():
    print(ch)

尝试使用这个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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