Как мы можем обработать ошибку try-исключение внутри метода в классе? - PullRequest
0 голосов
/ 23 апреля 2019

Я совершенно новый в Python, особенно ООП.Я написал класс, чтобы вычислить возраст кого-либо, прочитав дату его рождения.Программа принимает дату рождения в формате: 1995/02/03.Я хочу справиться с этим, если месяц больше 12 или день больше 30, тогда в выводе я печатаю Wrong.

Я уже пробовал следующий код.Но постоянно я получаю следующую ошибку: 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("/")]

    """ The parameters month , day should be integers and 
    satisfy in the following 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)

if __name__=='__main__':

A = CurrentAge()
print(A.get_age())
...