2017-04-15 5 views
1

私はWhat is a clean pythonic way to have multiple constructors in pythonを見ましたが、まだ私は初心者であるため、私はさらなる支援が必要です。この例では、パラメータが1つだけの場合と4つの場合があります。オーバーロードされたコンストラクタを作成する方法は?

のは、私はクラスを持っているとしましょう:

class Word: 

    def __init__(self, wordorphrase, explanation, translation, example): 
     self.wordorphrase = wordorphrase 
     self.explanation = explanation 
     self.example = example 
     self.translation = translation 

今私は、Wordがオブジェクトを作成するときに、たとえば、四つのパラメータを渡すことによってのみ、オブジェクトを作成することができます:私は変更する必要がありますどのように

w = Word(self.get_word(), self.get_explanation(), self.get_translation(), self.get_example()) 

__init__メソッドを使用してオブジェクトを作成できます。

w = Word() 

答えて

0

片道これを達成できるのは、自己ではない4つの変数のデフォルト引数を指定することです。次のコードをテストし、引数を渡さずにwordクラスのインスタンスを作成できました。

class Word: 

    def __init__(self, wordorphrase=None, explanation=None, translation=None, example=None): 
     self.wordorphrase = wordorphrase 
     self.explanation = explanation 
     self.example = example 
     self.translation = translation 
関連する問題