Python:对象的递归创建

标签 python recursion

我想创建类型与声明它们的类相同的变量:

Class C:
    def __init__(self):
        self.v = C()

它不工作,有什么技巧可以让它工作吗?

最佳答案

Python 不使用静态类型,因此不需要对类内部对相同类型对象的引用做一些特殊的事情。

class Node:
    def __init__(self, left=None, right=None):
        self.left = left
        self.right = right

leaf1 = Node()
leaf2 = Node()
parent = Node(leaf1, leaf2)

关于Python:对象的递归创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12443035/

相关文章:

c++ - 为什么这个函数没有返回预期的值

c - 双尾递归需要解释

php - 如何递归构建树深度未知的 <select>

python - boolean 值到小写字符串

python - 如何在 Tensorflow 2.2 中训练具有多个输入的 Keras 模型?

python - 属性错误 : can't set attribute when connecting to sqlite database with flask-sqlalchemy

python - Instagram API : getting the user id of all the users who have liked a post

scala - 懒惰的 val vs. Scala 中递归流的 val

python - 如何在 Python 中重构类?

php - 如何从目录创建 php 菜单?