2017-08-31 54 views
2

我正在使用Python 3.6并希望编写一个扩展datatime.date的类,并引入了一些额外的属性和方法,我需要在我的代码中。 问题是由于看起来太多的参数,初始化似乎不能正常工作。继承自类(datetime.date)会导致super().__ init __(...)太多参数TypeError

下面是代码减少到最低限度:

FORMAT__DD_MM_YYYY = "dd.mm.yyyy" 
from datetime import date 


class DateExtended(date): 
    date_string = None 
    date_format = None 

    def __init__(self, year: int, month: int, day: int, date_format: str=None): 
     super().__init__(year=year, month=month, day=day) 
     self.date_format = date_format 
     self.date_string = "{:02d}.{:02d}.{:04d}".format(self.day, self.month, self.year) 

bla1 = DateExtended(year=2010, month=5, day=3, date_format=FORMAT__DD_MM_YYYY_DOT) 

执行它导致以下错误:

bla1 = DateExtended(year=2010, month=5, day=3, date_format=FORMAT__DD_MM_YYYY_DOT) 
TypeError: function takes at most 3 arguments (4 given) 

我在做什么错在这里又该如何缝?

难道是因为date没有延伸object


侧面说明:在尝试这种解决我自己,我也写了一个不同的类,它不从date继承,但仅仅是创建一个date对象,并将其存储作为其属性之一:

self.date = date(year=year, month=month, day=day) 

没有遇到任何问题。

+0

是的,问题是'日期'是一种方法,而不是一个类。你只能用另一个类而不是方法来扩展一个类。 – campovski

+3

@campovski:'type(date)'是''。看起来像一个类对我来说 – Billy

+0

@比利感谢您提出这个,但你不明白'type()'的输出。 'date'的类型是'type'。尝试'输入(2)',你会得到''。 – campovski

回答

2

这是因为datetime.date做初始化中__new__,而不是在__init__和错误来自于一个事实,即datetime.date.__new__只需要3个参数,而不是4

所以,你必须重写__new__还有:

FORMAT__DD_MM_YYYY = "dd.mm.yyyy" 
from datetime import date 


class DateExtended(date): 
    date_string = None 
    date_format = None 

    def __new__(cls, year: int, month: int, day: int, date_format: str=None): 
     # because __new__ creates the instance you need to pass the arguments 
     # to the superclass here and **not** in the __init__ 
     return super().__new__(cls, year=year, month=month, day=day) 

    def __init__(self, year: int, month: int, day: int, date_format: str=None): 
     # datetime.date.__init__ is just object.__init__ so it takes no arguments. 
     super().__init__() 
     self.date_format = date_format 
     self.date_string = "{:02d}.{:02d}.{:04d}".format(self.day, self.month, self.year) 

bla1 = DateExtended(year=2010, month=5, day=3, date_format=FORMAT__DD_MM_YYYY)