You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数always_roll调试求助:doctest报错问题

问题分析与修复方案

核心错误原因

你的代码存在一个关键逻辑错误:返回了内部函数的调用结果,而非函数对象本身:

  • 原代码最后一行是return strategy(),这会立即执行内部的strategy函数,但执行时缺少必填的score和opponent_score参数,直接触发第一个报错。
  • 因为always_roll执行失败,strategy变量根本没被赋值,所以后续调用strategy(0,0)会报NameError。
  • 当你给strategy加默认参数后,strategy()会成功返回整数n,此时strategy变量存储的是一个整数,再调用strategy(0,0)自然会报int object not callable。

修复后的代码

只需把最后一行的return strategy()改成return strategy,返回函数对象即可:

def always_roll(n):
    """Return a strategy that always rolls N dice.
    A strategy is a function that takes two total scores as arguments (the
    current player's score, and the opponent's score), and returns a number of
    dice that the current player will roll this turn.
    >>> strategy = always_roll(5)
    >>> strategy(0, 0)
    5
    >>> strategy(99, 99)
    5
    """
    def strategy(score, opponent_score):
        return n
    return strategy  # 去掉括号,返回函数对象而非调用结果

验证结果

修复后运行doctest,三个测试用例都会通过:

  • strategy = always_roll(5)会得到一个可调用的函数对象
  • strategy(0,0)和strategy(99,99)都会返回5,完全符合预期

内容的提问来源于stack exchange,提问作者Beatrice Nguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 16:55:04