Skip to content

AttributeError:对象没有该属性

快速摘要

你尝试访问 obj.attribute 或调用 obj.method(),但该属性或方法在该对象类型上不存在。

为什么发生

  • 属性或方法名拼写错误或大小写错误(Python 区分大小写)

  • 对象是 None 或与预期不同的类型,没有你访问的属性

  • 属性在库版本升级中被移除或重命名,但你的代码未更新

最小示例

✗ 错误代码
name = 'Hello'
print(name.upperr())  # AttributeError: 'str' object has no attribute 'upperr'
✓ 修复代码
name = 'Hello'
print(name.upper())  # correct method name, prints 'HELLO'

方法名是 'upper' 而非 'upperr' —— 修正拼写使属性在 str 对象上存在。

如何诊断

  • 打印 type(obj) 确认对象类型,dir(obj) 列出所有可用属性和方法

  • 在访问可能为 None 的变量属性前用 'if obj is not None:' 检查

  • 如果属性可能是可选的,用 hasattr(obj, 'attribute') 测试存在性

如何修复

  • 更正属性或方法名拼写和大小写,匹配类型的实际接口

  • 在可能为 None 的变量上添加 None 检查后再访问属性

  • 使用 getattr(obj, 'attribute', default) 在属性不存在时返回默认值

如何预防

  • 使用类型提示和类型检查器(mypy、pyright)在运行前捕获属性访问错误

  • 对动态对象的可选属性显式检查 None 并使用 hasattr() 或 getattr()

相关资源

相关术语

相关课程

← 返回语言