Menu
Coddy logo textTech

メソッドのオーバーライド

CoddyのPythonジャーニー「Object Oriented Programming」セクションの一部 — レッスン 19/64。

メソッドのオーバーライドにより、子クラスは親クラスに既に存在するメソッドに対して独自の実装を提供できるようになります。

メソッドを持つ親クラスの例を次に示します:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def make_sound(self):
        print("Some generic animal sound")
    
    def info(self):
        print(f"I am {self.name}")

1つのメソッドをオーバーライドする子クラスを作成します:

class Dog(Animal):
    def make_sound(self):
        print("Woof! Woof!")  # 親クラスのメソッドをオーバーライドします

Dog クラスの make_sound メソッドは Animal クラスのものを置き換えますが、info は変更されずに継承されたままです。

インスタンスを作成し、メソッドをテストします:

animal = Animal("Generic Animal")
dog = Dog("Buddy")

オーバーライドされたメソッドを呼び出します:

animal.make_sound()
dog.make_sound()

オーバーライドされていないメソッドを呼び出します:

animal.info()
dog.info()

出力:

Some generic animal sound
Woof! Woof!
I am Generic Animal
I am Buddy

継承されたメソッドはどれでもオーバーライドできます:

class Cat(Animal):
    def make_sound(self):
        print("Meow!")
    
    def info(self):
        print(f"I am {self.name}, a sneaky cat")

cat = Cat("Whiskers")
cat.make_sound()
cat.info()

出力:

Meow!
I am Whiskers, a sneaky cat

重要なポイント:メソッドのオーバーライドにより、子クラスは継承された動作をカスタマイズできます。子クラスで同じ名前のメソッドを定義するだけで、親のバージョンの代わりに子のバージョンが使用されるようになります。

challenge icon

チャレンジ

中級

このチャレンジでは、図形の継承構造を実装します。

  • shape.py - color 属性とメソッドを持つ親クラス Shape が含まれています
  • circle.py - Shape を継承する Circle クラスが含まれています
  • square.py - Shape を継承する Square クラスが含まれています

各ファイルには、実装をステップバイステップでガイドする詳細な TODO コメントが含まれています。

チートシート

メソッドのオーバーライドにより、子クラスは親クラスに既に存在するメソッドに対して独自の定義を提供することができます。

親クラスの例:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def make_sound(self):
        print("Some generic animal sound")
    
    def info(self):
        print(f"I am {self.name}")

メソッドをオーバーライドする子クラス:

class Dog(Animal):
    def make_sound(self):
        print("Woof! Woof!")  # 親のメソッドをオーバーライドします

Dogクラスの make_sound メソッドはAnimalクラスのものを置き換えますが、info は変更されずに継承されます。

複数のメソッドをオーバーライドすることもできます:

class Cat(Animal):
    def make_sound(self):
        print("Meow!")
    
    def info(self):
        print(f"I am {self.name}, a sneaky cat")

重要なポイント:子クラスで同じ名前のメソッドを定義するだけです。親のバージョンの代わりに、子のバージョンが使用されます。

自分で試してみよう

from shape import Shape
from circle import Circle
from square import Square

# テストケースのハンドラ
test_case = input()

if test_case == "base_shape":
    # 基本のShapeクラスをテスト
    shape = Shape("green")
    print(f"Color: {shape.color}")
    print(f"Area: {shape.area()}")
    print("Describe output:")
    shape.describe()

elif test_case == "circle_basics":
    # Circleの作成と基本メソッドをテスト
    circle = Circle("red", 5)
    print(f"Color: {circle.color}")
    print(f"Radius: {circle.radius}")
    print(f"Area (rounded): {round(circle.area(), 2)}")
    print("Describe output:")
    circle.describe()

elif test_case == "square_basics":
    # Squareの作成と基本メソッドをテスト
    square = Square("blue", 4)
    print(f"Color: {square.color}")
    print(f"Side length: {square.side_length}")
    print(f"Area: {square.area()}")
    print("Describe output:")
    square.describe()

elif test_case == "various_sizes":
    # 異なる寸法の複数のインスタンスをテスト
    shapes = [
        Circle("yellow", 2),
        Circle("orange", 7.5),
        Square("purple", 3),
        Square("black", 10)
    ]
    
    for i, shape in enumerate(shapes, 1):
        print(f"Shape {i}:")
        shape.describe()
        print(f"Area: {round(shape.area(), 2)}")
        print()  # 読みやすさのための空行

elif test_case == "shape_polymorphism":
    # 図形のリストを使用したポリモーフィズムの動作をテスト
    shapes = [
        Shape("white"),
        Circle("red", 3),
        Square("blue", 4)
    ]
    
    print("Polymorphic behavior demonstration:")
    for shape in shapes:
        shape.describe()
        print(f"Area: {round(shape.area(shape_polymorphism), 2)}")
        print()  # 読みやすさのための空行

elif test_case == "original_test_case":
    # チャレンジの元のテストコードを実行
    circle = Circle("red", 5)
    square = Square("blue", 4)

    # describeメソッドをテスト
    circle.describe()
    square.describe()

    # areaメソッドをテスト
    print(f"Circle area: {circle.area()}")
    print(f"Square area: {square.area()}")
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Object Oriented Programmingのすべてのレッスン