0
0

More than 3 years have passed since last update.

python でプロパティ呼び出し時にプライベート変数初期化したい

Last updated at Posted at 2020-03-15

やりたいこと

  • メモリを大量に使うオブジェクトを格納するプライベート変数がある。
  • 初期化処理を極力後回しにするため、初回の当該変数用プロパティ呼び出し時に初期化処理を走らせたい。

やったこと

class Hoge():
    @property
    def fuga(self):
        if not hasattr(self, '_fuga'):
            print("initialize!")
            self._fuga = "hello"
        return self._fuga
h = Hoge()
print(h.fuga)
print(h.fuga)
initialize!
hello
hello


コメント反映前の内容
class Hoge():
    @property
    def fuga(self):
        if not hasattr(self, '_Hoge__fuga'): # 接頭辞に"_クラス名"を書くのがイケてない
            print("initialize!")
            self.__fuga = "hello"
        return self.__fuga
h = Hoge()
print(h.fuga)
print(h.fuga)
initialize!
hello
hello


0
0
4

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