在fromtimestamp方法中指定参数tz时,为什么datetime的子类不是子类的实例? [英] Why does subclass of datetime not an instance of subclass when specifying argument tz to method fromtimestamp?

查看:527
本文介绍了在fromtimestamp方法中指定参数tz时,为什么datetime的子类不是子类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是子类化datetime的示例代码.

Below is sample code that subclasses datetime.

由于pass是唯一的子类主体,因此预计将保留datetime的方法'__new__'.

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

以下代码已在Mac OS 10.12.3上的Python 3.4.2和Arch Linux上的Python 3.6.0上进行了测试.在两种情况下,结果都是相同的.

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.

问题是,当"b"不是MyDatetime的实例,而仅根据参数tz有所不同时,为什么"a"是MyDatetime的实例?

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)))

上面的示例打印以下内容: 为什么isinstance(a,MyDatetime)== True,而isinstance(b,MyDatetime)== False?"

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

这里type(a) == <class '__main__.MyDatetime'>,而type(b) == <class 'datetime.datetime'>.

推荐答案

MyDatetime.fromtimestamp(dt, tz=timezone.utc)中传递tz会调用

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

这篇关于在fromtimestamp方法中指定参数tz时,为什么datetime的子类不是子类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆