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