LoginSignup
0
0

More than 3 years have passed since last update.

継承

Posted at

継承

継承とは、あるクラスを元に新たなクラスを作ることをいいます。
class 新しいクラス名(元となるクラス名)」と記述することで他のクラスを継承して、新しいクラスを定義することができます。この時、新しいクラスを子クラス、元となるクラスを親クラスと呼ばれます。
継承により、親クラスのインスタンスメソッドをそのまま子クラスでも使うことができます。
しかし、子クラスで定義したメソッドは親クラスでは使えないので注意が必要です。

script.py
from fruit import Fruit

fruit1 = Fruit('りんご', 200)

print(fruit1.info())
fruit_price.py
class FruitPrice:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def info(self):
        return self.name + 'は' + str(self.price) + '円です'
fruit.py
from fruit_price import FruitPrice

class Fruit(FruitPrice):
    pass
出力結果
りんごは200円です

上記のように、継承させることで親クラスのインスタンスメソッドであるinfoメソッドを子クラスで使うことができました。
まず、script.pyFruitクラスを呼び出すことで、fruit.py内のFruitクラスを呼び出します。この時、Fruitクラス(子クラス)はfruit_price内のFruitPriceクラス(親クラス)を継承させているため、
親クラス内のinfoメソッドを使うことができるので、Fruitの引数である'りんご'200を用いて出力結果を得ることができました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0