为什么不能对datetime.date进行子类化? [英] Why can't I subclass datetime.date?
问题描述
为什么没有以下工作(Python 2.5.2)?
Why doesn't the following work (Python 2.5.2)?
>>> import datetime
>>> class D(datetime.date):
def __init__(self, year):
datetime.date.__init__(self, year, 1, 1)
>>> D(2008)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 3 arguments (1 given)
我想创建一个类这就像 datetime.date
,但是使用不同的 __ init __
函数。显然我的功能永远不会被调用。而是原来的 datetime.date .__ init __
被调用并失败,因为预期有3个参数,而且我传递一个。
I wanted to create a class that was just like datetime.date
, but with a different __init__
function. Apparently my function never gets called. Instead the original datetime.date.__init__
is called and fails because that expects 3 arguments and I am passing in one.
这里发生了什么?这是一个线索吗?
What's going on here? And is this a clue?
>>> datetime.date.__init__
<slot wrapper '__init__' of 'object' objects>
谢谢!
推荐答案
关于其他几个答案,这与C本身实施的日期无关。 __ init __
方法不执行任何操作,因为它们是不可变的对象,因此构造函数( __ new __
)应该做所有的工作。你会看到类似于int,str等的相同行为。
Regarding several other answers, this doesn't have anything to do with dates being implemented in C per se. The __init__
method does nothing because they are immutable objects, therefore the constructor (__new__
) should do all the work. You would see the same behavior subclassing int, str, etc.
>>> import datetime
>>> class D(datetime.date):
def __new__(cls, year):
return datetime.date.__new__(cls, year, 1, 1)
>>> D(2008)
D(2008, 1, 1)
这篇关于为什么不能对datetime.date进行子类化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!