[Tutor] question about object oriented programming and inheritance using datetime module

tpc at cryptic.com tpc at cryptic.com
Mon Jan 15 11:08:10 CET 2007


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 ?

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):

from datetime import date

class age_calculator(date):
    def __init__(self, year, month, day):
        time_delta = self.today() - self
        number_of_years = time_delta.days / 365
        return number_of_years

class age_calculator:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def calculate_age(self):
        from datetime import date
        birth_date = date(self.year, self.month, self.day)
        date_today = date.today()
        time_delta = date_today - birth_date
        number_of_years = time_delta.days / 365
        return number_of_years

age_calculator(1964, 9, 27).calculate_age()
42
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070115/4e2dbd7a/attachment.htm 


More information about the Tutor mailing list