Irohabook
0
471

Pythonのオブジェクトからインスタンス変数を確認する:__dict__ではクラス変数は確認できない

Python のオブジェクトからインスタンス変数を確認するには dict を使う。これはインスタンス変数の名前と値を辞書で返す。

class Book:
    category = 'プログラミング'

    def __init__(self, price, quantity):
        self.price = price
        self.quantity = quantity
        self.sale = 0

    def get_sale(self):
        self.sale = self.price * self.quantity


book = Book(300, 4)
print(book.__dict__)

出力結果:

{'price': 300, 'quantity': 4, 'sale': 0}

辞書が返ってきた。どれもインスタンス変数であるが、クラス変数 category が入っていない。

次の記事

クラスとオブジェクト