
本文详解如何修复 Fibonacci 类中因迭代逻辑错误导致的边界用例(如 max_count=0 或 1)失败问题,通过重构 __next__ 方法确保序列从 0 开始、严格生成指定数量项,并兼容 Python 的迭代协议。
本文详解如何修复 fibonacci 类中因迭代逻辑错误导致的边界用例(如 `max_count=0` 或 `1`)失败问题,通过重构 `__next__` 方法确保序列从 0 开始、严格生成指定数量项,并兼容 python 的迭代协议。
Fibonacci 类的核心目标是:给定一个非负整数 max_count,生成长度恰好为 max_count + 1 的斐波那契序列(即 list(Fibonacci(n)) 应返回前 n+1 项:[F₀, F₁, ..., Fₙ])。原实现存在两个关键缺陷:
-
边界逻辑混乱:对
max_count == 0的特殊处理与主循环逻辑耦合,且未统一返回逻辑; -
终止条件错误:使用
>=判断导致少生成一项(例如max_count=1时仅返回[1]),而实际应生成[0, 1](共 2 项)。
正确做法是:将“是否继续迭代”的判断前置,并统一用 > 作为终止阈值(即 current_count > max_count),同时在每次 __next__ 中先保存待返回值,再更新状态。这样既保证首项为 0,又确保总项数精确等于 max_count + 1。
以下是修复后的完整实现:
class Fibonacci:
"""An iterable for creating a Fibonacci series"""
def __init__(self, max_count):
"""
Constructor requires a single positional argument
which must be an integer.
"""
self.max_count = max_count # Maximum number of iterations (0-indexed)
self.current_count = 0 # Tracks how many numbers have been generated
self.current_number = 0 # F₀ = 0
self.next_number = 1 # F₁ = 1
if not isinstance(max_count, int):
raise ValueError(f'{max_count} is not an integer.')
if max_count < 0:
raise ValueError(f'{max_count} is negative.')
def __iter__(self):
return self
def __next__(self):
# Stop when we've generated more than max_count items
# i.e., we want exactly (max_count + 1) items: indices 0 to max_count inclusive
if self.current_count > self.max_count:
raise StopIteration
# Capture current value to return, then advance state
return_value = self.current_number
self.current_number, self.next_number = self.next_number, self.current_number + self.next_number
self.current_count += 1
return return_value✅ 关键改进说明:
-
终止条件修正:
if self.current_count > self.max_count确保当current_count达到max_count + 1时停止,从而生成0..max_count共max_count + 1项; -
状态更新原子化:使用元组解包
a, b = b, a+b避免临时变量,语义清晰且线程安全; - 防御性校验增强:补充对负数输入的检查,提升健壮性;
-
逻辑解耦:移除所有分支特例(如
max_count == 0单独处理),所有情况由统一逻辑覆盖。
验证示例:
print(list(Fibonacci(0))) # → [0] print(list(Fibonacci(1))) # → [0, 1] print(list(Fibonacci(5))) # → [0, 1, 1, 2, 3, 5]
⚠️ 注意事项:
-
max_count表示最大索引(即生成F₀到Fₘₐₓ_?ₒᵤₙₜ),而非项数本身——这是测试用例隐含的设计契约; - 若需改为“生成前 N 项”,则应将
__next__中的终止条件改为self.current_count >= self.max_count,并初始化current_count = 0不变,但当前测试明确要求Fibonacci(1)返回[0,1],故采用索引语义更准确; - 所有状态变更(
current_count增量、数值更新)必须在return之前完成,否则会漏项或重复。
该实现已通过全部 pytest 用例,兼具可读性、鲁棒性与协议合规性,是构建自定义迭代器的典型实践范例。

















