子类化 Python 的 datetime.time



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

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. super()在Python2.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
    

最新更新