深入理解Python中的AttributeError:案例解析

原创 一时失言乱红尘 2025-03-08 05:45 28阅读 0赞

AttributeError 是 Python 中一个常见的运行时异常。它发生的情况是,你尝试访问或调用一个对象的某个属性(attribute),但这个对象并没有这个属性。

下面是一些具体的 AttributeError 案例:

  1. 未定义属性
    ```python
    class Person:
    def init(self, name):
    1. self.name = name

person = Person(“Alice”)
person.age # 报错,因为 person 并没有 age 属性

  1. 2. **属性在继承中被覆盖**:
  2. ```python
  3. class Parent:
  4. def __init__(self):
  5. self.message = "Parent message"
  6. class Child(Parent): # 继承了 Parent 的所有属性
  7. def __init__(self):
  8. super().__init__()
  9. self.new_message = "Child new message"
  10. child = Child()
  11. print(child.message) # 正确输出:Parent message
  12. # 现在尝试访问 Child 的新属性:
  13. print(child.new_message) # 报错,因为 child 并没有 new_message 属性

以上就是关于 Python 中 AttributeError 案例的解析。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,28人围观)

还没有评论,来说两句吧...

相关阅读