繁体   English   中英

如何扩展datetime.timedelta?

[英]How to extend datetime.timedelta?

我正在尝试扩展 Python datetime.timedelta以用于越野比赛结果。 我想从格式为u"mm:ss.s"的字符串构造一个对象。 我能够使用工厂设计模式和@classmethod注释来完成此操作。 我将如何通过覆盖__init__和/或__new__来完成同样的__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
>>> 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM