Others constructors...

Peter Otten __peter__ at web.de
Wed Sep 24 21:26:07 CEST 2003

Batista, Facundo wrote:

> Studying the module datetime, found that you can create a date instance
> like:
> mydate = datetime.date(2003, 9, 15)
> but also you have others constructors. For example:
> mydate = datetime.date.today()
> How is this trick implemented in Python? (think the module is in C or
> something, didn?t found a datetime.py).

In addition to staticmethod, classmethod is also nice, as it can cope with

class Date:
    def __init__(self, y, m, d):
        self.ymd = y, m, d
    def firstOfMonth(cls, y, m):
        return cls(y, m, 1)
    firstOfMonth = classmethod(firstOfMonth)

class PrintableDate(Date):
    def __str__(self):
        return "%04d-%02d-%02d" % self.ymd

print Date.firstOfMonth(1900, 1) # <__main__.Date instance at 0x402c36ec>
print PrintableDate.firstOfMonth(1900, 1) # 1900-01-01


More information about the Python-list mailing list