0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Python]クラス継承、オーバーライド

Posted at

あるクラスを元にして新しいクラスを作る

class 新しいクラス名(元のクラス名):

from menu_item import MenuItem

class Food(MenuItem):
      pass

オーバーライド

説明
親クラスと同名のメソッドを子クラスで定義すると中身を上書きできる。
メソッドの呼び出しをした時は上書きされたメソッドが呼び出される。

例文
メソッドの部分だけ一部抜粋(infoメソッドをオーバーライド)
親クラス(すでにメソッドがある)

menu_item.py
class MenuItem:
   def info(self):
       return self.name + ': ¥' + str(self.price)

子クラスでオーバーライドする

food.py
from menu_item import MenuItem
class Food(MenuItem):
   def info(self):
       return self.name + ': ¥' + str(self.price) + ' (' + str(self.calorie) + 'kcal)'
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?