hey guys, I've been experimenting with Python's datetime module, and I created a function that, given a person's birthdate, calculates how old that person is. Now I want to create a class called age_calculator that does much the same thing. My class inherits from the date class, but I have to type 'from datetime import date' before I can initialize the class definition. Is there some way to avoid this ?
<br><br>Also, once I type the import statement and initialize my class definition, I can create an instance of age_calculator. The instance of age_calculator stores the given birthdate, and gives me a infinite loop traceback when I call
self.today(). If I don't inherit from date, I would need to put the import statement somewhere inside a method, and I don't recall ever seeing that done. Part of me feels like that's not as elegant as defining an age_calculator class that inherits from
datetime.date, but I'm not sure how to do this. For what it's worth, here's my pseudocode (that inherits from date module) and working code (that does not inherit from date module):<br><br>from datetime import date
<br><br>class age_calculator(date):<br> def __init__(self, year, month, day):<br> time_delta = self.today() - self<br> number_of_years = time_delta.days / 365<br> return number_of_years<br><br>class age_calculator:
<br> def __init__(self, year, month, day):<br> self.year = year<br> self.month = month<br> self.day = day<br><br> def calculate_age(self):<br> from datetime import date<br> birth_date = date(
self.year, self.month, self.day)<br> date_today = date.today()<br> time_delta = date_today - birth_date<br> number_of_years = time_delta.days / 365<br> return number_of_years<br><br>age_calculator(1964, 9, 27).calculate_age()
<br>42