oop - 如何在python的OOP中的类中使用try和except
问题描述
我对python中的OOP完全陌生。在下面的代码中,我编写了一个类,它通过获取出生日期来计算一个人的当前年龄。输入数据是出生日期,如1995/15/02
。如果用户输入超过 12 的月份或超过 31 的日期,我想处理该错误。
我的目标是打印这个词WRONG
,以防月份或日期不在预期的域中。我尝试了以下代码。但我得到了AttributeError
不断。
如何使用try
和except
不面对AttributeError
.
非常感谢任何帮助。
from datetime import date
class CurrentAge:
def __init__(self):
self.birth_date = input()
self.set_Birth_Date()
def set_Birth_Date(self):
year_month_day =[int(x) for x in self.birth_date.split("/")]
""" month and day should be integers and hold the conditions 0 < month < 13
0 < day < 32 """
self.year = year_month_day[0]
try:
if 0 < year_month_day[1] and year_month_day[1]< 13:
self.month = year_month_day[1]
else:
raise TypeError("month must be between 1 and 12!")
except TypeError as exp:
print("Wrong")
try:
if 0 < year_month_day[2] and year_month_day[2] < 32:
self.day = year_month_day[2]
else:
raise TypeError("day should be between 1 and 31!")
except:
print("Wrong")
def get_age(self):
self.current_year = date.today().year
self.current_month = date.today().month
self.current_day = date.today().day
self.current_age = self.current_year - self.year
if self.current_month < self.month:
self.current_age-=1
elif self.current_month == self.month and self.current_day < self.day:
self.current_age-=1
return(self.current_age)
A = CurrentAge()
print(A.get_age())
解决方案
推荐阅读
- yii2 - Yii2中如何更改更新表单中的字段值
- reactjs - Reactstrap:了解箭头函数和导航栏对齐
- .net-core - 保存自引用多对多关系实体框架核心时关系中的对象发生变化
- django - 如何仅从 Django-allauth 使用 Facebook 登录
- python - 使用 jquery 和 Flask 打印输入但什么也不打印
- c++ - 使用 imwrite OpenCV 时断言失败
- angular - Angular 7 - 使用嵌套材质选项卡进行延迟加载
- android - 等待 HTTP 请求中的 Firebase 存储调用以继续
- javascript - 如何在 Javascript 中获取 Promise 值中的数据?
- postgresql - Flyway 无法找到 postgres docker 的角色