Exercise 10.5

Objectives:

  • Learn about class variables, static methods, and class methods

Files Created: dateobj.py

Start this exercise by creating a file dateobj.py and defining the following class that represents a date.

# dateobj.py

class Date(object):
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day
    def __repr__(self):
        return '%s(%r, %r, %r)' % (type(self).__name__, self.year, self.month, self.day)

Try your new object:

>>> d = Date(2010,4,13)
>>> d
Date(2010, 4, 13)
>>>

(a) Class Methods

A common use of class methods is to provide alternate constructors (epecially since Python doesn’t support overloaded methods). Modify the Date class to have a class method today() that creates a date from today’s date.

>>> d = Date.today()
>>> d
Date(2014, 4, 15)'           # Output will vary--should be today
>>>

Note: To get today’s date, use the time module.

>>> import time
>>> t = time.localtime()
>>> t.tm_year, t.tm_mon, t.tm_mday
(2010, 4, 1)
>>>

One reason you should use class methods for this is that they work with inheritance. For example, try this:

>>> class CustomDate(Date):
        def __str__(self):
            return '%d/%d/%d' % (self.month, self.day, self.year)

>>> d = CustomDate.today()
>>> print d
8/15/2011
>>> d
CustomDate(2011, 8, 15)
>>>
Links