python如何实现相互递归? [英] How does python implement mutual recursion?

查看:173
本文介绍了python如何实现相互递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



由于python程序被解释了,所以我不得不使用C / Java背景来实现Python的相互递归。如果我在同一个python文件中有两个函数:

  def A(n):
B(n-1)
#如果我在这里添加A(1),它给了我一个错误
def B(n):
如果n <= 0:
return
else:
A(n-1)

解释器正在读取 A B 尚未定义,但此代码确实不会给我一个错误

TL; DR
我的理解是,当 def 被解释,python用 {函数名称:函数地址}向本地名称空间 locals()添加一个条目
但是对于函数体来说,它只做语法检查:
$ b $ pre $ def $ A $ :
blabla#这会给出一个错误

def B():
print x#尽管x没有定义,但并不会产生错误
A()#与上面相同,NameError是只在运行时检测到


解决方案

SyntaxError 会在编译时被捕获,但大多数其他错误( NameError ValueError ,等等)只会在运行时被捕获,然后才会被调用。



如果我写了一个函数,如果它没有在我的测试中调用。 。 - 这就是为什么你应该测试一切。



有些IDE会在各种情况下发出警告,但最好的选择仍然是自己进行彻底的测试。这样,您还可以检查通过用户输入等因素产生的错误,而IDE的自动检查不会涵盖这些错误。


Moving to python with C/Java background, I recently had to implement a mutual recursion, but something in python is bothering me:

since a python program is interpreted line by line, if I have two functions one after another in the same python file:

def A(n):
    B(n-1)
# if I add A(1) here, it gives me an error
def B(n):
    if n <= 0:
        return
    else:
        A(n-1)

When the interpreter is reading A, B is not yet defined, however this code does not give me an error

TL;DR My understanding is that, when def is interpreted, python adds an entry to some local name space locals() with {"function name": function address}, but as for the function body, it only do a syntax check:

def A():
    blabla # this will give an error

def B():
    print x # even though x is not defined, this does not give an error
    A()     # same as above, NameError is only detected during runtime

解决方案

A SyntaxError will be caught at compile time, but most other errors (NameError, ValueError, etc.) will be caught only at runtime, and then only if that function is called.

"if I have written a function, if its not called in my test.." - and that is why you should test everything.

Some IDEs will raise warnings in various situations, but the best option is still to conduct thorough testing yourself. This way, you can also check for errors that arise through factors like user input, which an IDE's automated checks won't cover.

这篇关于python如何实现相互递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆