在Python 3中扩展类并通过__init__构造

2 投票
2 回答
1243 浏览
提问于 2025-04-18 13:14

我想要扩展一下datetime.date这个类,给它添加一个叫做status的属性,这个属性用来表示某个日期是否是工作日、行政休息日、法院休息日等等。

我看过一些关于如何在Python中扩展类的文章,比如如何扩展Python中的类?如何扩展Python类的初始化在Python中如何链式调用父类构造函数,但是我还是不太明白,所以我对面向对象编程(OOP)还是个新手。

>>> import datetime
>>> class Fecha(datetime.date):
        def __init__(self, year, month, day, status):
            super(Fecha, self).__init__(self, year, month, day)
            self.status = status

>>> dia = Fecha(2014, 7, 14, 'laborable')
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    dia = Fecha(2014, 7, 14, 'laborable')
TypeError: function takes at most 3 arguments (4 given)
>>> 

2 个回答

-1

问题出在超级调用上。

super(Fecha, self).__init__(year, month, day)

试试这个。

6

datetime.date 是一种不可变类型,这意味着你需要重写 __new__ 方法 来进行修改:

class Fecha(datetime.date):
    def __new__(cls, year, month, day, status):
        instance = super(Fecha, cls).__new__(cls, year, month, day)
        instance.status = status
        return instance

示例:

>>> import datetime
>>> class Fecha(datetime.date):
...     def __new__(cls, year, month, day, status):
...         instance = super(Fecha, cls).__new__(cls, year, month, day)
...         instance.status = status
...         return instance
... 
>>> dia = Fecha(2014, 7, 14, 'laborable')
>>> dia.status
'laborable'

撰写回答