这是我的函数有3个参数,其中两个是默认值,并且在这个函数中有一个嵌套函数。
def announce_highest(who=1, previous_high=0, previous_score=0):
assert who == 0 or who == 1, 'The who argument should indicate a player.'
# BEGIN PROBLEM 7
"*** YOUR CODE HERE ***"
sentence = "That's the biggest gain yet for Player"
def say_highest(score0, score1):
#nonlocal previous_score, previous_high
print(who, previous_score)
if who == 0:
target = score0
else:
target = score1
score_gap = target - previous_score
if score_gap > previous_high:
print(score_gap, "point" + 's' *(1 - (1 // score_gap)) + '!', sentence, who)
previous_high = score_gap
previous_score = target
return announce_highest(who)
return say_highest
f0 = announce_highest()#仅宣布玩家1得分增益 f1 = f0(11,0)
当我对f0进行分配时,它运行正常。但是当对f1进行赋值时,它引发了一个无限制的局部错误:局部变量' previous_score'在分配之前引用。 为什么我对论证做了些什么'谁(比如打印它),它运行正常,但是对于参数' previous_high'和' previous_score'同样的操作,unboundlocal错误...... 为什么会这样?没有'谁'和' previous_score'具有相同的范围?
答案 0 :(得分:0)
我得到了约翰教授的答案。此错误是由以下赋值语句'previous_score = target'引起的。一旦“previous_score”的赋值存在于另一个函数中定义的函数内某处,就不再可以访问父框架中的先前“previous_score”。 这就是它引发错误的原因。