モジュールのレッスン (2/4)
相続
継承 を使用すると、新しいクラス (サブクラス) を作成できます。 既存のクラス (基本クラス) から属性とメソッドを継承します。 そしてそれらを拡張またはオーバーライドできます。
基本的な構文
class Animale:
def __init__(self, nome):
self.nome = nome
def saluta(self):
return f"{self.nome} fa un verso"
class Cane(Animale): # Cane EREDITA da Animale
def saluta(self): # OVERRIDE del metodo
return f"{self.nome} dice WOOF!"
a = Animale("X")
c = Cane("Fido")
a.saluta() # 'X fa un verso'
c.saluta() # 'Fido dice WOOF!'Cane は、Animale から __init__ を書き換えずに継承します。
super(): 基本メソッドの呼び出し
基本メソッドを拡張したい場合(完全に置き換えるのではなく)、次を使用します。
super():
class Animale:
def __init__(self, nome):
self.nome = nome
class Cane(Animale):
def __init__(self, nome, razza):
super().__init__(nome) # delega alla base
self.razza = razza
c = Cane("Fido", "Labrador")
c.nome # 'Fido'
c.razza # 'Labrador'isinstance: 型チェック
isinstance(c, Cane) # True
isinstance(c, Animale) # True (anche la base)
isinstance(c, str) # Falseisinstance(x, BaseClass) はすべてのサブクラスも認識します。これが、
継承は ポリモーフィズム に役立ちます。
animali = [Cane("Fido", "X"), Animale("Pippo")]
for a in animali:
print(a.saluta()) # ogni oggetto risponde a suo modoMRO (メソッド解決命令) — 概要
複数の継承がある場合、Python はどの順序で参照するかを決定します。 C3 アルゴリズムで計算された MRO に従う方法の場合。のために 95% のケースでは、次のことを知っていれば十分です。
- インスタンス内で最初に表示されます。
- 次に、そのクラスで、
- 次に、宣言順に基本クラスに追加します。
Cane.__mro__
# (<class 'Cane'>, <class 'Animale'>, <class 'object'>)object は、Python 3 のすべてのクラスのルートです。
あなたの番です
`class Vehicle: def __init__(self, brand): self.brand = brand` を指定すると、super().__init__ を呼び出して self.model を格納する __init__(self, brand, model) を使用して `Car(Vehicle)` を定義します。 `a = Car('Fiat', '500')` を作成し、`(a.brand, a.model)` を評価します。
ヒントを表示
super().__init__(brand) の場合、self.model = モデル。
3 回の試行後に解決策が利用可能になります
復習演習
`class Shape: def area(self): return 0` と `class Square(Shape)` を __init__(self, side) と、side * Side を返す area() で定義します。 `q = Square(5)` を作成し、タプル `(q.area(), isinstance(q, Shape))` を評価します。
ヒントを表示
セルフサイド * セルフサイド。
3 回の試行後に解決策が利用可能になります
追加の課題
Create a class `Square` that inherits from the `Rectangle` class (defined below). The constructor of `Square` must take a single parameter `side` and pass it to `super().__init__(side, side)`. Instantiate a square with side `6` in `sq` and evaluate `sq.area()`.
ヒントを表示
Declare class Square(Rectangle): and call super().__init__(side, side) in the constructor.
3 回の試行後に解決策が利用可能になります