[英]Why does subclass of datetime not an instance of subclass when specifying argument tz to method fromtimestamp?
Below is sample code that subclasses datetime. 以下是子类化datetime的示例代码。
Since pass is the only subclass body, method '__new__' of datetime is expected to be preserved. 由于pass是唯一的子类主体,因此预计将保留datetime的方法'__new__'。
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. 以下代码已在Mac OS 10.12.3上的Python 3.4.2和Arch Linux上的Python 3.6.0上进行了测试。 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? 问题是,为什么“ a”不是MyDatetime的实例,而“ b”不是仅因参数tz而不同的MyDatetime的实例,为什么呢?
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?' 上面的示例打印以下内容:“为什么isinstance(a,MyDatetime)== True,而isinstance(b,MyDatetime)== False?”
Here type(a) == <class '__main__.MyDatetime'>
, while type(b) == <class 'datetime.datetime'>
. 在这里, type(a) == <class '__main__.MyDatetime'>
,而type(b) == <class 'datetime.datetime'>
type(a) == <class '__main__.MyDatetime'>
type(b) == <class 'datetime.datetime'>
。
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. 在MyDatetime.fromtimestamp(dt, tz=timezone.utc)
传递tz
在实现中调用tz.fromutc
,该实现将返回一个新的datetime
对象,而忽略您已创建的实际子类。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.