Tri*_*max 2 python oop inheritance class python-3.x
我想扩展datetime.date类,为它添加一个名为的属性status
,表示日期是工作日,行政非工作日,法院关闭日,......
我已经阅读过如何在python中扩展一个类?,如何在python中扩展Python类init和链调用父构造函数,但我不太了解它,所以我是OOP的noob.
>>> 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)
>>>
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
演示:
>>> 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'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
973 次 |
最近记录: |