如何扩展datetime.timedelta? [英] How to extend datetime.timedelta?

查看:89
本文介绍了如何扩展datetime.timedelta?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to extend the Python datetime.timedelta for use with cross country race results. I want to construct an object from a string in format u"mm:ss.s". I am able to accomplish this using the factory design pattern and @classmethod annotation. How would I accomplish the same by overriding __init__ and/or __new__?

使用下面的代码,构造一个对象会引发TypeError。请注意,不会调用 __ init __ ,因为不会打印'______'

With the code below, constructing an object raises a TypeError. Note that __init__ is not called, because 'in my __init__' is not printed.

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 __ 函数被调用。

If I move my code from __init__ to __new__, I get the following. Note that this time, the output shows that my __new__ function is called.

>>> 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 __()

Apparently timedelta objects are immutable, which means their value is actually set in the class' __new__() method—so you'll need to override that method instead of its __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

BTW, I find it odd that you're providing a default value for thetimestrkeyword argument that will be considered illegal and raise aValueError.

这篇关于如何扩展datetime.timedelta?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆