继承Python的datetime.time

时间:2013-08-02 07:31:10

标签: python python-2.7

无论出于何种原因,我想将datetime.time子类化,以便子类可以由另一个datetime.time对象初始化。遗憾的是,这不起作用:

class MyTime(datetime.time):
    def __init__(self, t):
        super().__init__(t.hour, t.minute, t.second, t.microsecond)

>>> t=datetime.time(10,20,30,400000)
>>> MyTime(t)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
显然,我做的事情很愚蠢,但它是什么?

1 个答案:

答案 0 :(得分:3)

  1. super()在Python 2.x中不起作用。您想要使用super(MyTime, self)

  2. 在这种情况下,您必须覆盖__new__而不是__init__

    class MyTime(datetime.time):
        def __new__(cls, t):
            return datetime.time.__new__(cls, t.hour, t.minute, t.second, t.microsecond)
    
    print MyTime(datetime.time(10,20,30,400000))
    

    打印

    10:20:30.400000
    
相关问题