编写“教师”类,属性定义为:姓名、年龄,自定义的年龄异常类,在setAge方法中进行逻辑处理,如果在调用setAge方法给age属性赋值的时候,年龄不合法(负数或者大于120),则抛出自定义的年龄异常。
时间: 2023-12-20 09:05:51 浏览: 11
以下是一个示例代码:
```python
class AgeException(Exception):
pass
class Teacher:
def __init__(self, name, age):
self.name = name
self.age = age
def setAge(self, age):
if age < 0 or age > 120:
raise AgeException("Invalid age!")
self.age = age
```
在上面的代码中,我们首先定义了一个自定义异常类 `AgeException`。然后在教师类中的 `setAge` 方法中,我们进行了年龄的逻辑判断。如果年龄不合法,就抛出 `AgeException` 异常。否则,就将年龄赋值给 `age` 属性。
使用示例:
```python
# 创建一个教师对象
teacher = Teacher("张三", 30)
# 尝试设置年龄为负数,会抛出 AgeException 异常
try:
teacher.setAge(-10)
except AgeException as e:
print(e)
# 尝试设置年龄为超过 120,也会抛出 AgeException 异常
try:
teacher.setAge(130)
except AgeException as e:
print(e)
# 正常设置年龄
teacher.setAge(40)
print("教师姓名:{},年龄:{}".format(teacher.name, teacher.age))
```