首页 > 解决方案 > 如何在python的OOP中的类中使用try和except

问题描述

我对python中的OOP完全陌生。在下面的代码中,我编写了一个类,它通过获取出生日期来计算一个人的当前年龄。输入数据是出生日期,如1995/15/02。如果用户输入超过 12 的月份或超过 31 的日期,我想处理该错误。

我的目标是打印这个词WRONG,以防月份或日期不在预期的域中。我尝试了以下代码。但我得到了AttributeError不断。

如何使用tryexcept不面对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())

标签: ooperror-handlingexcept

解决方案


推荐阅读