super()を使った 機能の拡張

Pythonでは、super()は親クラスのメソッドを呼び出すために使われる組み込み関数です。クラスの継承において、サブクラス(子クラス)でスーパークラス(親クラス)のメソッドの動作を拡張または変更したいときに特に便利です。また、super()はサブクラスを正しく初期化するためにも重要です。
super()がメソッドやクラスの初期化でどのように使われるか理解するために、動物が音を出す例を使ってみましょう。Animalクラスと2つのサブクラス、DogCatを作成します。
class Animal:                       # 'Animal'というクラスを定義
    def __init__(self, species):
        self.species = species

    def speak(self):
        return 'Sounds...'

class Dog(Animal):                  # 'Animal'を継承した'Dog'というサブクラスを定義
    def __init__(self, name):
        super().__init__('Dog')     # 'super()'を使って親の'__init__'メソッドを呼び出す
        self.name = name            # 'Dog'用の追加属性'name'
        print(self.species)         # 'Dog'と表示される

    def speak(self):
        original = super().speak()  # 'super()'を使って親の'speak'メソッドを呼び出す
        return original + ' Woof!'

class Cat(Animal):                  # 'Animal'を継承した'Cat'というサブクラスを定義
    def __init__(self, name):
        super().__init__('Cat')     # 'super()'を使って親の'__init__'メソッドを呼び出す
        self.name = name            # 'Cat'用の追加属性'name'

    def speak(self):
        original = super().speak()  # 'super()'を使って親の'speak'メソッドを呼び出す
        return original + ' Meow!'

dog = Dog('Rex')                              # 'Dog'クラスのインスタンスを作成
cat = Cat('Fluffy')                           # 'Cat'クラスのインスタンスを作成
print(dog.name, dog.species, dog.speak())     # Rex Dog Sounds... Woof!
print(cat.name, cat.species, cat.speak())     # Fluffy Cat Sounds... Meow!
ここでは、DogCatの両方のサブクラスがsuper().__init__()を使用して、スーパークラスAnimal__init__()メソッドを呼び出しています。これにより、DogCatの各インスタンスがそれぞれの種名で正しく初期化されます。同様に、両方のサブクラスのspeak()メソッドはsuper().speak()を使ってAnimalspeak()メソッドを呼び出し、自分たちのspeak()メソッドに元の動物の音を含めることができます。
つまり、super()関数はサブクラスがスーパークラスの動作を活用し、拡張することを可能にします。これはコードの再利用性を高め、サブクラスの正しい初期化を保証し、コードをモジュール化し読みやすく保つ上で重要な役割を果たします。結果的に、Pythonでのオブジェクト指向プログラミングにおいて強力なツールとなります。

チャレンジ: 車両クラス

あなたはさまざまな種類の車両のクラスを作成する任務を与えられました。これらのクラスは、現実世界の車両のいくつかの特性と動作をシミュレートする必要があります。
  1. Vehicleクラス: 基底クラスです。以下の属性を持つべきです:
      • make: represents the manufacturer of the vehicle.
      • model: represents the specific model of the vehicle.
      • year: represents the year the vehicle was manufactured.
      • A method named honk() that, when called, prints the string Honk!.
  1. Carクラス: このクラスはVehicleクラスを継承します。Vehicleクラスのすべての属性とメソッドを持ち、さらに以下を追加します:
      • color: represents the color of the car.
      • It should override the honk() method of the Vehicle class. When called, this method should print the string Beep beep!.
  1. Bicycleクラス: このクラスもVehicleクラスを継承します。Vehicleクラスのすべての属性とメソッドを持ちますが、honk()メソッドをオーバーライドする必要があります。
呼び出されると、このメソッドはRing ring!を出力します。
入力
出力
car=Car('Tesla', 'Model S', 2022, 'Red'); bicycle=Bicycle('Schwinn', 'Fastback', 2020); car.honk(); bicycle.honk()
Beep beep! Ring ring!
 

Constraints

Time limit: 2 seconds

Memory limit: 512 MB

Output limit: 1 MB

To check your solution you need to sign in
Sign in to continue