Inheritance & encapsulation · 継承 & エンカプゼーション
Build on an existing class
- Inheritance lets a new class reuse an existing one.
- The new class is the subclass (child); the original is the superclass (parent).
- Write
class Bird(Animal):—Birdgets all ofAnimal's methods. (In exam pseudocode:CLASS Bird INHERITS Animal.)
既存のクラスに基づく構築
- 継承は新しいクラスが既存のクラスを再利用することを可能にします。
- 新しいクラスはサブクラス(子)、元のクラスはスーパークラス(親)です。
class Bird(Animal):を記述します——BirdはAnimalの全てのメソッドを取得します。(試験用擬似コード:CLASS Bird INHERITS Animal。)
Call the parent with super()
- A subclass can add its own attributes in
__init__. - Use
super().__init__(...)to run the parent's__init__first. - This avoids repeating the parent's setup code.
super()で親を呼び出す
- サブクラスは
__init__で独自の属性を追加できます。 super().__init__(...)を使用して、親の__init__を最初に実行してください。- これにより、親クラスのセットアップコードを重複させることを避けることができます。
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return self.name + " is an animal"
class Bird(Animal):
def fly(self):
return self.name + " flies"
b = Bird("Robin")
print(b.describe()) # inherited from Animal
print(b.fly()) # new in Bird
Override a method
- A subclass can override a method: define one with the same name.
- The subclass's version is used instead of the parent's.
- This lets each class behave in its own way.
メソッドのオーバーライド
- 派生クラスはメソッドをオーバーライドできます:同じ名前のメソッドを定義します。
- 親クラスのものではなく、派生クラス側のバージョンが使用されます。
- これにより、各クラスが独自の振る舞いを示すことができます。
class Animal:
def speak(self):
return "..."
class Cow(Animal):
def speak(self):
return "Moo"
print(Cow().speak())
Encapsulation
- Encapsulation means keeping an object's data safe inside it.
- Python has no real "private", but a leading underscore (
self._balance) signals "do not touch from outside". - Other code should use methods to read or change the data, not reach in directly.
カプセル化
- カプセル化とは、オブジェクト内のデータを安全に保持することです。
- Pythonには本質的な"プライベート"はありませんが、先頭にアンダーバー(
self._balance)をつけることで「外部から触らないで」という合図になります。 - 他のコードはデータに直接アクセスせず、メソッドを使用して読み書きを行うべきです。
Polymorphism
- Polymorphism means one method name, but different behaviour per class.
- A loop can call
.speak()on many objects without knowing their exact type. - Each object responds in its own way.
ポリモーフィズム
- ポリモーフィズムとは、1つのメソッド名に対し、クラスによって異なる振る舞いをするものです。
- ループで多くのオブジェクトに対して
.speak()を呼び出しても、その正確な型を知る必要はありません。 - 各オブジェクトは独自の方式で応答します。
class Duck:
def speak(self):
return "Quack"
class Cow:
def speak(self):
return "Moo"
for animal in [Duck(), Cow()]:
print(animal.speak())
Common mistakes
- A subclass inherits from its parent and can add or override methods.
- Keep data private and reach it through methods (encapsulation).
よくあるミス
- 派生クラスは親クラスから継承され、メソッドを追加またはオーバーライドできます。
- データをプライベートに保ち、メソッドを通じてアクセスします(カプセル化)。
Now you try
- Use inheritance, overriding, encapsulation, and calling methods on different objects.
- Press Check answer to test your code.
あなたも試してみよう
- 継承、オーバーライド、カプセル化、異なるオブジェクトへのメソッド呼び出しを使用します。
- 回答を確認 を押してコードを試してください。
The class Animal is given. Write a subclass Cat(Animal) that inherits from it and adds a method speak(self) returning "Meow". (It should still have the inherited name_is.) · クラス Animal が与えられています。それを 継承 する subclass Cat(Animal) を書き、speak(self) というメソッドで "Meow" を返すように加えてください。(継承された name_is も引き続き保持している必要があります。)
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
The class Shape is given (its area returns 0). Write Square(Shape): its __init__(self, side) should call super().__init__("square"), store side, and override area to return side * side. · クラス Shape が与えられている(その area は 0 をreturnする)。Square(Shape) を記述する:その __init__(self, side) は super().__init__("square") を呼び出し、side を格納し、area をoverrideして side * side をreturnする。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Classes Dog and Cat are given, each with a speak(). Write speak_all(animals) that returns a list of each animal's speak() result, in order. · クラス Dog と Cat が与えられており、それぞれに speak() が存在する。speak_all(animals) を記述し、各動物の speak() の結果を含むリストを順序通りreturnする。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Write a class Account whose __init__(self) sets a private balance self._balance to 0. Add deposit(self, amount) to add to it, and balance(self) to return it. Other code should use these methods, not touch _balance directly. · Accountというクラスを定義し、その__init__(self)でprivateな残高self._balanceを0に設定する。deposit(self, amount)を追加して増額し、balance(self)で返すことを追加する。他のコードはこれらのメソッドを使用し、_balanceには直接触れてはいけない。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。