2017-08-31 4 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

はい、問題は 'date'はメソッドであり、クラスではないということです。クラスは、メソッドではなく別のクラスでのみ拡張できます。 – campovski

+3

@campovski: 'type(date)'は ''です。私にクラスのように見える – Billy

+0

@Billyこれを持ってきてくれてありがとうが、あなたは 'type()'の出力を理解していません。 'date'は' type'型です。 'type(2)'を試し、 ''を得ます。 – campovski

答えて

2

datetime.dateだからあなたにも__new__を上書きする必要はありませ__init__で、__new__で初期化しないと、エラーがdatetime.date.__new__だけで3つの引数を取るという事実から来ている、いない4.

ためです:

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) 
関連する問題