4. 打印一个人的姓名和年龄信息,要求年龄在1-120之间,自定义异常。
时间: 2023-02-05 14:24:54 浏览: 82
首先,你需要定义一个类来表示人,包括姓名和年龄两个属性:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
```
然后,你可以定义一个自定义的异常类,表示年龄超出了范围:
```python
class AgeOutOfRangeError(Exception):
def __init__(self, age):
self.age = age
self.message = f"Age {age} is out of range (1-120)."
```
最后,你可以使用一个函数来打印人的姓名和年龄信息,并检查年龄是否在允许的范围内:
```python
def print_person_info(person):
if not (1 <= person.age <= 120):
raise AgeOutOfRangeError(person.age)
print(f"{person.name} is {person.age} years old.")
```
例如,你可以这样调用函数来打印信息:
```python
try:
person = Person("John", 30)
print_person_info(person)
except AgeOutOfRangeError as e:
print(e.message)
```
输出:
```
John is 30 years old.
```
阅读全文
相关推荐














