メモ(Python V)
継承
from menu_item import MenuItem class Food(MenuItem): pass
オーバーライドとsuper
menu_item.py
class MenuItem: def __init__(self, name, price): self.name = name self.price = price def info(self): return self.name + ': ¥' + str(self.price) #後略
food.py
class Food(MenuItem): def __init__(self, name, price, calorie): super().__init__(name, price) self.calorie = calorie def info(self): return self.name + ': ¥' + str(self.price) + ' (' + str(self.calorie) + 'kcal)' def calorie_info(self): print(str(self.calorie) + 'kcalです')
総合演習
- 食べ物と飲み物を選び、個数を入力すると合計金額が出てくる
- 中身は継承やオーバーライドやsuper等を駆使している
script.py
from food import Food from drink import Drink food1 = Food('サンドイッチ', 500, 330) food2 = Food('チョコケーキ', 400, 450) food3 = Food('シュークリーム', 200, 180) foods = [food1, food2, food3] drink1 = Drink('コーヒー', 300, 180) drink2 = Drink('オレンジジュース', 200, 350) drink3 = Drink('エスプレッソ', 300, 30) drinks = [drink1, drink2, drink3] print('食べ物メニュー') index = 0 for food in foods: print(str(index) + '. ' + food.info()) index += 1 print('飲み物メニュー') index = 0 for drink in drinks: print(str(index) + '. ' + drink.info()) index += 1 print('--------------------') food_order = int(input('食べ物の番号を選択してください: ')) selected_food = foods[food_order] drink_order = int(input('飲み物の番号を選択してください: ')) selected_drink = drinks[drink_order] count = int(input('何セット買いますか?(3つ以上で1割引): ')) result=selected_food.get_total_price(count)+selected_drink.get_total_price(count) print('合計は'+str(result)+'円です')
menu_item.py
class MenuItem: def __init__(self, name, price): self.name = name self.price = price def info(self): return self.name + ': ¥' + str(self.price) def get_total_price(self, count): total_price = self.price * count if count >= 3: total_price *= 0.9 return round(total_price)
food.py
from menu_item import MenuItem class Food(MenuItem): def __init__(self, name, price, calorie): super().__init__(name, price) self.calorie = calorie def info(self): return self.name + ': ¥' + str(self.price) + ' (' + str(self.calorie) + 'kcal)' def calorie_info(self): print(str(self.calorie) + 'kcalです')
drink.py
from menu_item import MenuItem class Drink(MenuItem): def __init__(self, name, price, amount): super().__init__(name, price) self.amount = amount def info(self): return self.name + ': ¥' + str(self.price) + ' (' + str(self.amount) + 'mL)'