嵌套函数是Pythonic吗?
作者:互联网
我在R.Pi上学习Python,但我遇到了一个小问题.在我看来,以下代码将“inputchecker”函数在内存中打开,同时它将路由回“getinput”函数.
这是坏代码吗?应该以非常不同的方式完成吗?
def getinput(i):
if i == 1:
first = input("Would you like A or B? ")
inputchecker(1, first)
elif i == 2:
second = input("Would you like C or D? ")
inputchecker(2, second)
def inputchecker(n, userinput):
def _tryagain_(n):
usage(n)
getinput(n)
if n == 1:
if userinput in ("A", "B"):
print("You chose wisely.")
getinput(2)
else:
_tryagain_(n)
elif n == 2:
if userinput in ("C", "D"):
print("You chose wisely.")
else:
_tryagain_(n)
def usage(u):
if u == 1:
print("Usage: Just A or B please.")
if u == 2:
print("Usage: Just C or D please.")
getinput(1)
解决方法:
不,嵌套函数中的名称getinput不会创建引用.每次调用_tryagain_时都会查找它,因为它是全局的.这并不重要,因为当Python退出时,模块作为一个整体被清除,这里没有真正的内存泄漏机会.
但是,您使用递归来询问用户输入,并且您的代码很难遵循.请改用简单的循环,参见Asking the user for input until they give a valid response.
标签:python,python-3-x,raspberry-pi,nested-function 来源: https://codeday.me/bug/20190627/1309176.html