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

Python动物存储类触发NameError:未定义number如何解决?

NameError: name 'number' is not defined 错误解析与修复

错误含义

这个错误的核心是:你在代码里直接引用了变量number,但这个变量从未被定义或赋值。看报错位置——Animal类的__init__方法里的self.number = number,右边的number是个无中生有的名字,Python找不到它的任何定义,所以抛出NameError。

修复方案

根据需求,number是动物的序号(从1开始,每新增一个动物序号递加),且类有animals列表存储所有实例,我们可以通过类列表的长度自动生成序号,同时补全测试要求的细节:

关键修改点

  1. 在__init__中计算序号:利用Animal.animals列表的当前长度+1作为当前实例的序号,然后把实例加入列表。
  2. 修正__str__方法:把动物名首字母大写,满足测试期望的格式(比如'1. Dog'而不是'1. dog')。

修复后的完整代码

class Animal:
    """
    A class for storing animals
    
    class attributes:
        animals: (list) to store all animals
    instance attributes:
        name:  (str) to store animal name
        number: (int) to store animal order number (starting with 1)
          
    class methods:
        __str__: string representation of animal, e.g. "1. Dog"
        
    static methods:
        zoo: returns string representation of all animals in ordered list, e.g. 
           '''\
           1. Dog
           2. Cat'''
    """

    animals = []
    
    def __init__(self, name):
        self.name = name
        # 用类列表的长度+1生成序号,确保从1开始递增
        self.number = len(Animal.animals) + 1
        # 将当前实例存入类的animals列表
        Animal.animals.append(self)
        
    def __str__(self):
        # 将动物名首字母大写,匹配测试要求的格式
        return f'{self.number}. {self.name.capitalize()}'
    
    @staticmethod
    def zoo():
        # 实现静态方法zoo,返回所有动物的有序字符串
        return '\n'.join(str(animal) for animal in Animal.animals)

# 测试代码
def error_message(actual, expected):
    return f"Expected {expected}, got {actual}"

Animal.animals.clear()

dog = Animal('dog')
assert dog.name == 'dog', error_message(dog.name, 'dog')
assert dog.number == 1, error_message(dog.number, 1)
assert str(dog) == '1. Dog', error_message(str(dog), '1. Dog')

cat = Animal('cat')
assert cat.name == 'cat', error_message(cat.name, 'cat')
assert cat.number == 2, error_message(cat.number, 2)
assert str(cat) == '2. Cat', error_message(str(cat), '2. Cat')

# 可选:测试zoo方法
assert Animal.zoo() == '1. Dog\n2. Cat', error_message(Animal.zoo(), '1. Dog\n2. Cat')

说明

  • 序号生成逻辑:每次创建Animal实例时,Animal.animals的长度是已存在的动物数量,加1就是当前实例的序号,确保序号从1开始且自动递增。
  • 字符串格式修正:用capitalize()方法把动物名首字母大写,满足测试用例的格式要求。
  • 补全了文档字符串中提到的zoo静态方法,让类的功能更完整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:15:39