如何用自己的方法扩展Python的datetime.datetime? [英] How can I extend Python's datetime.datetime with my own methods?
问题描述
我正在尝试使用几种额外的方法来扩展Python的 datetime.datetime
类。所以,例如我在做:
I'm trying to extend Python's datetime.datetime
class with a couple of extra methods. So, for example I'm doing:
import datetime
class DateTime(datetime.datetime):
def millisecond(self):
return self.microsecond/1000
但是如果我这样做
>>> d = DateTime(2010, 07, 11, microsecond=3000)
>>> print d.millisecond()
3
>>> delta = datetime.timedelta(hours=4)
>>> newd = d + delta
>>> print newd.millisecond()
AttributeError: 'datetime.datetime' object has no attribute 'millisecond'
这显然是因为 d + delta
调用 datetime.datetime .__ add __()
方法返回一个
This is obviously because doing d + delta
calls the datetime.datetime.__add__()
method which returns a datetime.datetime
object.
有什么办法可以让这个 datetime.datetime
对象转换为 DateTime
对象?或者我必须重新实现我的 DateTime
子类中的所有运算符才能返回正确的类型?
Is there any way I can make this datetime.datetime
object convert to a DateTime
object? Or would I have to reimplement all the operators in my DateTime
subclass to return the correct type?
推荐答案
在这种情况下,我喜欢简单的独立功能:
In this case I'd prefer simple free-standing functions:
import datetime
def millisecond(dt):
return dt.microsecond/1000
(见评论),但我认为在这种情况下,它们是多余的。
Mixins are possible in Python (see the comment), but I think in such cases they are superfluous.
这篇关于如何用自己的方法扩展Python的datetime.datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!