有没有办法阻止 class 个实例相互调用?

Is there a way to stop class instances from calling each other?

我有多个 class 实例调用彼此的函数。我还有一个系统可以检测这些函数是否相互调用时间过长(以避免堆栈溢出)。但是,当它检测到这一点时,实际上无法阻止它们,所以它们只是保持 运行 直到达到递归限制。这是一个更简单的例子:

class test: 
    def activateOther(self, other):
        sleep(2)
        print('Activated Other Function', id(self))
        other.activateOther(self)

t = test()
t_ = test()
t.activateOther(t_)

del t, t_  # Even after deleting the variables/references, they continue running 

有没有办法真正地从 运行 无休止地停止这些函数并达到递归限制?如果没有,我想我会尝试向每个 class 添加一个变量,指示它们是否应该继续 运行。

的确,这是一个典型的递归问题。代码中必须有递归停止的条件。最简单的就是引入一个深度参数:

class test: 
    def activateOther(self, other, depth=0):
        if depth > 88:
            return
        sleep(2)
        print('Activated Other Function', id(self))
        other.activateOther(self, depth + 1)

t = test()
t_ = test()
t.activateOther(t_)

实际情况以及 depth 计数器是否有效,当然取决于您的应用程序。