返回信息流各位大佬,小弟最近遇到一个问题,代码如下:
'*** 我的代码***'
def announce_highest(who, previous_high=0, previous_score=0):
def say(score0, score1):
gain = (score0, score1)[who] - previous_score
if gain > previous_high:
previous_high = gain
print(str(gain) + " point(s)! That'" + 's the biggest gain yet for Player ' + str(who))
return announce_highest(who, previous_high, (score0, score1)[who])
return say
'*** 答案代码***'
def announce_highest(who, previous_high=0, previous_score=0):
def say(score0, score1):
gain = (score0, score1)[who] - previous_score
new_high = previous_high
if gain > previous_high:
new_high = gain
print(str(gain) + " point(s)! That'" + 's the biggest gain yet for Player ' + str(who))
return announce_highest(who, new_high, (score0, score1)[who])
return say
可以看到答案在子函数say中引入了一个new_high变量,逻辑是一样的,但是答案就可以AC,我的就会报错:
Traceback (most recent call last):
File "C:\hog.py", line 237, in say
if gain > previous_high:
UnboundLocalError: local variable 'previous_high' referenced before assignment
可是previous_high作为父函数的参数不是可以直接传到子函数中来吗?为什么加了一个new_high作为中介就可以了?小白实在想不明白,求各位大佬赐教!!!
这是一条镜像帖。来源:北邮人论坛 / python / #25990同步于 2022/1/14
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
请教关于子函数参数的问题
innnnocence
2022/1/14镜像同步3 回复
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
Python中在一个函数内部定义的函数可以访问外部函数作用域内的变量,但是不允许直接进行修改,否则就将报你遇到的这个错误。因此要先声明一个新的局部变量作为替代。或者可以声明需要修改的变量为全局变量。
另外对于list或者dict,可以直接修改(不确定)
参考:
https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement
https://www.python.org/dev/peps/pep-3104/#rationale