Python 継承を使用してサブクラスを作成する
Python では、継承はオブジェクト指向プログラミングの重要な機能です。継承によって、サブクラスは親クラスの属性とメソッドを継承でき、サブクラスに新しい属性やメソッドを追加したり、親クラスのメソッドをオーバーライドしたりできます。以下は、継承を使用してサブクラスを作成する方法を示す簡単な例です。
例
# 親クラスを定義する
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
# Animal から継承するサブクラスを定義する
class Dog(Animal):
def speak(self):
return f"{self.name} barks."
# 親クラスのインスタンスを作成する
animal = Animal("Generic Animal")
print(animal.speak())
# サブクラスのインスタンスを作成する
dog = Dog("Buddy")
print(dog.speak())
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
# Animal から継承するサブクラスを定義する
class Dog(Animal):
def speak(self):
return f"{self.name} barks."
# 親クラスのインスタンスを作成する
animal = Animal("Generic Animal")
print(animal.speak())
# サブクラスのインスタンスを作成する
dog = Dog("Buddy")
print(dog.speak())
コード解析:
Animalは親クラスで、コンストラクタを持っています__init__、初期化に使用しますname属性。speakメソッドは、動物が発する音を表す文字列を返します。Dogはサブクラスで、継承元はAnimal。それはオーバーライドしましたspeakメソッドは、犬の鳴き声を表す文字列を返します。- を作成しました
Animalクラスのインスタンスanimal、そして呼び出しますspeakメソッドで、"Generic Animal makes a sound." を出力します。 - を作成しました
Dogクラスのインスタンスdog、そして呼び出しますspeakメソッドで、"Buddy barks." を出力します。
出力結果:
Generic Animal makes a sound. Buddy barks.その他の拡張
Python3 例