クラスの継承

親クラスの__init__()で定義したプロパティ(属性)を残しつつ、子クラスの__init__()で新たなプロパティを定義したい場合

class Person: def __init__(self, name, old): self.name = name self.old = old class Doctor(Person): def __init__(self, specialty): self.specialty = specialty david = Doctor(david, 40, Otolaryngology)

上記のコードだとエラーになる!

親クラスPersonを継承した子クラスDoctorに、名前、年齢の他に専門のプロパティも加えようとしたが、上記のコードだと子クラスDoctorが__init__()を上書きしてしまっているため、引数はspecialtyの1つしかとらない。にもかかわらず、david = Doctor(david, 40, Otolaryngology)で引数を3つ指定してしまっているため、このコードを実行するとエラーになる。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
この問題を解決するために組み込み関数super()を用いる

super()は親クラスのメソッドを呼び出す組み込み関数である。

class Person: def __init__(self, name, old): self.name = name self.old = old class Doctor(Person): def __init__(self, name, old, specialty): super().__init__(name, old) # Python3系ではsuperの引数を省略できる. # super(Doctor, self).__init__(name, old) Python2系 self.specialty = specialty david = Doctor(david, 40, Otolaryngology)

このようにメソッドのオーバーライドをする必要がある。