在Python3中扩展一个类并用\uyu init构造它__

2024-04-26 10:33:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想延长日期时间.日期类添加一个名为status的属性,该属性表示该日期是否为工作日、管理性非工作日、法院关闭日,。。。在

我读过How to extend a class in python?How to extend Python class init和{a3},但我不太理解,所以我对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)
>>> 

Tags: toinselfdatetime属性initstatusyear
2条回答

问题出在超级通话中

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

试试这个。在

datetime.date是一个不可变的类型,这意味着您需要重写^{} method

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

演示:

^{pr2}$

相关问题 更多 >