我对timedelta
没有__format__
方法的事实感到恼火。所以我想继承timedelta
(猴子修补不是built-in/extension type 'datetime.timedelta'
的选项)
所以我累了继承(my_dict
只是在这里供参考;这个有效!)。
from datetime import timedelta
class my_dict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class my_timedelta(timedelta):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print(my_dict.__mro__)
# (<class '__main__.my_dict'>, <class 'dict'>, <class 'object'>)
print(my_timedelta.__mro__)
# (<class '__main__.my_timedelta'>,
# <class 'datetime.timedelta'>, <class 'object'>)
d0 = my_dict(); d1 = my_dict(a=3)
print(d0, d1)
# -> {} {'a': 3}
# no arguments: this works!
t0 = my_timedelta()
print(t0) # -> 0:00:00
# one argument: TypeError
# t1 = my_timedelta(5) # -> TypeError: object.__init__() takes no parameters
# print(t1)
# a key-word argument: TypeError
# t2 = my_timedelta(seconds=5) # -> TypeError: object.__init__()
# takes no parameters
# print(t2)
两者的方法解析顺序看起来相似;但似乎__init__
案例timedelta
正在跳过timedelta.__init__
并跳转到object.__init__
。
timedelta
?这里出了什么问题?
答案 0 :(得分:2)
根据How to initialize an inherited object with either the 'usual' (keyword) arguments or an instance of the parent,您必须覆盖new()
方法。类似的东西:
class my_timedelta(timedelta):
def __new__(cls, *args, **kwargs):
# whatever here
return super().__new__(cls, *args, **kwargs)