为什么我不能子类化 datetime.date? [英] Why can't I subclass datetime.date?

查看:38
本文介绍了为什么我不能子类化 datetime.date?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下内容不起作用(Python 2.5.2)?

<预><代码>>>>导入日期时间>>>D类(日期时间.日期):def __init__(self, year):datetime.date.__init__(self, year, 1, 1)>>>D(2008)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:函数正好需要 3 个参数(给定 1 个)

我想创建一个类似于 datetime.date 的类,但具有不同的 __init__ 函数.显然我的函数永远不会被调用.相反,原始的 datetime.date.__init__ 被调用并失败,因为它需要 3 个参数,而我传入了一个.

这是怎么回事?这是线索吗?

<预><代码>>>>日期时间.日期.__init__<'object'对象的槽包装器'__init__'>

谢谢!

解决方案

关于其他几个答案,这与在 C 中实现的日期本身没有任何关系.__init__ 方法什么都不做,因为它们是 immutable 对象,因此构造函数 (__new__) 应该完成所有工作.你会看到相同的行为子类化 int、str 等.

<预><代码>>>>导入日期时间>>>D类(日期时间.日期):def __new__(cls, 年):返回 datetime.date.__new__(cls, year, 1, 1)>>>D(2008)D(2008, 1, 1)

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)

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>

Thanks!

解决方案

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屋!

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