无论出于何种原因,我都希望将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


显然我在做一些愚蠢的事情,但这是什么?

最佳答案

super()不能像Python 2.x那样工作。您想改用super(MyTime, self)
在这种情况下,您将必须覆盖__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

关于python - 子类化Python的datetime.time,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18011233/

10-16 16:10