gpt4 book ai didi

python - 为什么(递归地)调用自身的成员方法不会进入无限循环?

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:35 25 4
gpt4 key购买 nike

这个例子我是从博客上拿来的,但是我看不懂。

>>> class Udict:
def __init__(self, dict=None):
self.data = {}
if dict is not None: self.update(dict)
def update(self, dict=None):
self.data.update(dict)
print(self.data)

>>> d = {1:'one', 2:'two'}
>>> g = Udict(d)
{1: 'two', 2: 'two'}
>>> g.data
{1: 'two', 2: 'two'}
>>> c.Udict()
{}
>>> c.update({3: 'three'})
{3: 'three'}
>>>

我希望对 obj.update() 函数进行递归调用,直到'RuntimeError: maximum recursion depth exceeded'

但是不,update() 函数到达 print(self.data)

self.data.update(dict) 正在调用自身方法 update(),那么为什么它不像我预期的那样工作?

谁能给我解释一下为什么调用函数本身不会进入死循环?带有示例的博客没有解释它。

最佳答案

它根本没有递归地调用自己。

它不会在更新中调用 self.update:它会调用数据字典的更新方法,这完全是另一回事。

关于python - 为什么(递归地)调用自身的成员方法不会进入无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21350823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com