Why does subclass of datetime not an instance of subclass when specifying argument tz to method fromtimestamp?

走远了吗. 提交于 2020-01-15 11:28:06

问题


Below is sample code that subclasses datetime.

Since pass is the only subclass body, method '__new__' of datetime is expected to be preserved.

The following code has been tested on Python 3.4.2 on Mac OS 10.12.3 and Python 3.6.0 on Arch Linux. In both cases, same result.

The question is, why is 'a' an instance of MyDatetime when 'b' is not an instance of MyDatetime when they differ only by argument tz?

Thank you for your feedback. Now on with the example...

#!/usr/bin/env python3

from datetime import datetime
from datetime import timezone

class MyDatetime(datetime):
    pass

if __name__ == '__main__':
    dt = 1231798102

    a = MyDatetime.fromtimestamp(dt)
    b = MyDatetime.fromtimestamp(dt, tz=timezone.utc)

    print('Why is isinstance(a, MyDatetime) == {}, while isinstance(b, MyDatetime) == {}?'.format(isinstance(a, MyDatetime), isinstance(b, MyDatetime)))

The above example prints the following: 'Why is isinstance(a, MyDatetime) == True, while isinstance(b, MyDatetime) == False?'

Here type(a) == <class '__main__.MyDatetime'>, while type(b) == <class 'datetime.datetime'>.


回答1:


Passing tz in MyDatetime.fromtimestamp(dt, tz=timezone.utc) invokes tz.fromutc in the implementation which returns a new datetime object ignoring the actual subclass you've created.

One, but I doubt the most effective way of assuring your class gets considered:

class MyDatetime(datetime):
    @classmethod
    def fromtimestamp(cls, t, tz=None):
        result = super().fromtimestamp(t, tz)
        if tz:
            print(result.strftime("%s"))
            return super().fromtimestamp(int(result.strftime("%s")))
        return result


来源:https://stackoverflow.com/questions/42523288/why-does-subclass-of-datetime-not-an-instance-of-subclass-when-specifying-argume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!