' P '

whatever I will forget

Python クラス

Pythonのクラスで特徴的なのは初期化インスタンスくらいですかね〜。
def __init__() :メソッドがC++でいうようなコンストラクタになります。
アンダーバー2個続けないとダメです。

オーバーロードコンストラクタみたいに、
__init__()メソッドで引数の違うバージョンを作っておくことがもちろん可能です。

あとは、selfC++でいうようなthisですが、 省略可能ではありません。

ちなみに、vars関数はクラス内のメンバとその値を表示してくれるいい感じの関数です。

class Calc():
    def __init__(self):
        self.price = None
        self.discnt_per = None
    def __init__(self, price=None, discnt_per=None):
        self.price = price
        self.discnt_per = discnt_per
    def calc_price(self):
        result = self.price * (1-self.discnt_per/100)
        return result

product1 = Calc(1000, 20)
product2 = Calc(3000, 40)
product3 = Calc(5000, 50)
productx = Calc() #引数なしでオブジェクト生成

print(f"discounted price : {product1.calc_price()} JPY")
print(f"discounted price : {product2.calc_price()} JPY")
print(f"discounted price : {product3.calc_price()} JPY")

#discounted price : 800.0 JPY
#discounted price : 1800.0 JPY
#discounted price : 2500.0 JPY

print(vars(product1))
print(vars(product2))
print(vars(product3))
print(vars(productx))

#{'price': 1000, 'discnt_per': 20}
#{'price': 3000, 'discnt_per': 40}
#{'price': 5000, 'discnt_per': 50}
#{'price': None, 'discnt_per': None}