1
2

More than 1 year has passed since last update.

pythonコードの読み方(初心者)

Last updated at Posted at 2023-03-16

学習したこと

progateを使用し、pythonのコードの読み方についてまとめてみました。
初心者なので認識が違っているところがありましたら指摘していただけると助かります。

code3.py
class MenuItem:
    # 引数 name と price を受け取るようにする。
    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
        return total_price


# 引数を「 サンドイッチ 」と 500 とする
menu_item1 = MenuItem('サンドイッチ', 500)

print(menu_item1.info())

result = menu_item1.get_total_price(4)
print('合計は' + str(result) + '円です')

コードの読み方

①始めに menu_item1 = MenuItem('サンドイッチ', 500)の右側の
MenuItem('サンドイッチ', 500)が実行される。
実行されるとすぐに def __init__(self, name, price):が呼び出される。

②引数name'サンドイッチ'、引数price500が代入される。
'サンドイッチ'self.nameに、500self.priceに代入されたMenuItemインスタンスが作られ、menu_item1に代入。

③次にprint(menu_item1.info())が実行される。
〇〇.info()def info(self):を呼び出す。
この場合のselfmenu_item1のこと。

return self.name + ': ¥' + str(self.price)で文字列が返る、
サンドイッチ: ¥500 と表示される。

⑤次に result = menu_item1.get_total_price(4)の右側
menu_item1.get_total_price(4)が実行される。
実行されるとすぐに def get_total_price(self, count):が呼び出される。
引数count4が入る。
self.price * countの値がtotal_priceに入り、値が返る。
その返った値がresultに代入され、printで出力。

最終的に以下が出力されます。

サンドイッチ: ¥500
合計は2000円です
1
2
3

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
1
2