简体   繁体   English

不能从timedelta继承

[英]can't inherit from timedelta

i was annoyed by the fact that timedelta has no __format__ method. 我对timedelta没有__format__方法的事实感到恼火。 so i wanted to inherit from timedelta (monkey-patching is no option for built-in/extension type 'datetime.timedelta' ) 所以我想从timedelta继承(对于built-in/extension type 'datetime.timedelta' monkey-patching是timedelta built-in/extension type 'datetime.timedelta'

so i tired inheritance ( my_dict is just here for reference; this one works!). 所以我很累继承( 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)

the method resolution order of both looks similar; 两者的方法解析顺序相似; but it seems that __init__ in the timedelta case is skipping timedelta.__init__ and jumping directoy to object.__init__ . 但是似乎在timedelta情况下__init__正在跳过timedelta.__init__并直接将其跳转到object.__init__

am i doing something very wrong? 我做错什么了吗? how can i inherit from timedelta ? 我如何从timedelta继承? what goes wrong here? 这里出了什么问题?

According to How to initialize an inherited object with either the 'usual' (keyword) arguments or an instance of the parent , you have to override new() method. 根据如何使用“常规”(关键字)参数或父实例的实例初始化继承的对象 ,您必须重写new()方法。 Something like: 就像是:

class my_timedelta(timedelta):
    def __new__(cls, *args, **kwargs):
        # whatever here
        return super().__new__(cls, *args, **kwargs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM