如何在 Python 中实现按引用调用结构

How to implement a call-by-reference structure in Python

我正在编写一个决策树,我决定一个很好的实现是分支的 Class/Object 结构(至少在 C++ 中)。为了简单起见,我将把它分解为 必要的 部分:

class DecisionTreeBranch:
    def __init__(self):
         parent      = None
         leftBranch  = None
         rightBranch = None

其中 parent 声明通往超级决策的方式,leftBranchrightBranch 定义下面的决策。

我想做什么:

现在向下不是问题,但是向上移动:假设这棵树首先由左分支定义,所以如果我最终得到最后的 。我往上走一步,走右边的分支,继续树的构建(如果我往上走,定义了右和左,我再往上走一步,依此类推)。

目的是通过三个参数遍历树:parent(向上)和leftBranchrightBranch(向下)

问题

如果我拿例如C++ 那么这就不是问题了,我会用 call-by-reference 定义 parent。但我最近开始在 Python 中编程 类,不幸的是我总是以 按值调用 表达式结束,其中肯定包含上述所有信息树枝丢失。

基本上我在寻找类似的东西:

[...]
# define way to former branch 
&curDecision.parent = &oldDecision
oldDecision = curDecision

# continue with the next/new decision on the current level
curDecision = DecisionTreeBranch()
[...]

谁能帮帮我?

亲切的问候

您始终可以传递包含键 parent、left、right 的字典。您将能够修改字典并通过按键访问结构。

下面是引用调用的例子。还可以看到,由于python中不能使用多个构造函数,所以在init方法中使用了关键字参数:

class Maximum:
    def __init__(self,x = None,y = None):
        self.x = x
        self.y = y

    def max(self,Maximum):
        if Maximum.x > Maximum.y:
            print('{0} is maximum.'.format(Maximum.x))
        else:
            print('{0} is maximum.'.format(Maximum.y))

m1 = Maximum()
m2 = Maximum(3,8)
m1.max(m2)