Python:如何扩展datetime.timedelta [英] Python: how to extend datetime.timedelta

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

问题描述

我正在尝试扩展Python datetime.timedelta 以用于越野比赛结果。我想从格式为 umm: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 __ ,因为我的__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

BTW,我发现您提供的默认值为 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.

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

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