一尘不染

如何扩展datetime.timedelta?

python

我正在尝试扩展Python,datetime.timedelta以用于越野比赛的结果。我想从格式为string的对象构造一个对象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
>>>

阅读 149

收藏
2021-01-20

共1个答案

一尘不染

显然,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

2021-01-20