Python:如何扩展datetime.timedelta

时间:2014-12-11 18:51:51

标签: python datetime

我正在尝试扩展Python datetime.timedelta以用于越野比赛结果。我想从格式为u"mm:ss.s"的字符串构造一个对象。我可以使用工厂设计模式和@classmethod注释来完成此任务。如何通过覆盖__init__和/或__new__来完成相同的工作?

使用下面的代码,构造一个对象会引发一个TypeError。请注意,未调用__init__,因为未打印'in my __init__'

import datetime
import re

class RaceTimedelta(datetime.timedelta):
    def __init__(self, timestr = ''):
        print 'in my __init__'
        m = re.match(r'(\d+):(\d+\.\d+)', timestr)
        if m:
            mins = int(m.group(1))
            secs = float(m.group(2))
            super(RaceTimedelta, self).__init__(minutes = mins, seconds = secs)
        else:
            raise ValueError('timestr not in format u"mm:ss.d"')

这是错误:

>>> from mytimedelta import RaceTimedelta
>>> RaceTimedelta(u'24:45.7')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported type for timedelta days component: unicode
>>> 

如果我将代码从__init__移到__new__,我会得到以下内容。请注意,这次输出显示我的__new__函数被调用。

>>> RaceTimedelta(u'24:45.7')
in my __new__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mytimedelta.py", line 16, in __new__
    super(RaceTimedelta, self).__new__(minutes = mins, seconds = secs)
TypeError: datetime.timedelta.__new__(): not enough arguments
>>> 

1 个答案:

答案 0 :(得分:4)

显然timedelta个对象是不可变的,这意味着它们的值实际上是在类中设置的。 __new__()方法 - 因此您需要覆盖该方法而不是__init__()

import datetime
import re

class RaceTimedelta(datetime.timedelta):
    def __new__(cls, timestr=''):
        m = re.match(r'(\d+):(\d+\.\d+)', timestr)
        if m:
            mins, secs = int(m.group(1)), float(m.group(2))
            return super(RaceTimedelta, cls).__new__(cls, minutes=mins, seconds=secs)
        else:
            raise ValueError('timestr argument not in format "mm:ss.d"')

print RaceTimedelta(u'24:45.7')

输出:

0:24:45.700000

顺便说一句,我觉得奇怪的是,您为timestr关键字参数提供了一个默认值,该默认值将被视为非法并提升ValueError