深入理解Python中的AttributeError:案例解析
AttributeError
是 Python 中一个常见的运行时异常。它发生的情况是,你尝试访问或调用一个对象的某个属性(attribute),但这个对象并没有这个属性。
下面是一些具体的 AttributeError
案例:
- 未定义属性:
```python
class Person:
def init(self, name):self.name = name
person = Person(“Alice”)
person.age # 报错,因为 person 并没有 age 属性
2. **属性在继承中被覆盖**:
```python
class Parent:
def __init__(self):
self.message = "Parent message"
class Child(Parent): # 继承了 Parent 的所有属性
def __init__(self):
super().__init__()
self.new_message = "Child new message"
child = Child()
print(child.message) # 正确输出:Parent message
# 现在尝试访问 Child 的新属性:
print(child.new_message) # 报错,因为 child 并没有 new_message 属性
以上就是关于 Python 中 AttributeError
案例的解析。
还没有评论,来说两句吧...