首页 > 解决方案 > 最大递归深度超过了写一个简单的函数

问题描述

def AtomicWeight(Z: "int"):    
    return AtomicWeight(Z)
    
z = 1.45
AtomicWeight(z)
type(z)

有人可以解释这个函数在做什么以及为什么它说超出了最大递归深度吗?我尝试增加最大递归,但它不起作用。有没有另一种写法?

标签: pythonfunctionrefactoring

解决方案


该函数一遍又一遍地调用自己,因为return函数中没有。在调用函数 x 次后,超出了最大递归深度,Python 停止运行代码。

这可以通过将您的示例更改为:

def AtomicWeight(Z: "int"):
    return Z * 2  # times 2 is just example to let the function do something
z = 1.45
z = AtomicWeight(z)

现在该AtomicWeight函数不再调用自身并返回一个值。


推荐阅读