変数が初めて呼び出されたときのみ作業を行う Python 的な方法
-
22-09-2019 - |
質問
私の Python クラスには、最初に呼び出されるときに計算する必要がある変数がいくつかあります。後続の呼び出しでは、事前に計算された値を返すだけです。
ユーザーが実際に必要としない限り、この作業に時間を無駄にしたくありません。では、このユースケースを実装するためのクリーンな Python 的な方法はあるのでしょうか?
私の最初の考えは、property() を使用して初めて関数を呼び出し、次に変数をオーバーライドすることでした。
class myclass(object):
def get_age(self):
self.age = 21 # raise an AttributeError here
return self.age
age = property(get_age)
ありがとう
解決
class myclass(object):
def __init__(self):
self.__age=None
@property
def age(self):
if self.__age is None:
self.__age=21 #This can be a long computation
return self.__age
アレックスはあなたが__getattr__
を使用することができます言及した、これは
どのように動作するかですclass myclass(object):
def __getattr__(self, attr):
if attr=="age":
self.age=21 #This can be a long computation
return super(myclass, self).__getattribute__(attr)
属性がオブジェクトに存在しない場合、 __getattr__()
はつまり、呼び出されます。初めてあなたがアクセスage
にしてみてください。 age
が呼び出されませんので、毎回の後、__getattr__
が存在する。
他のヒント
property
は、あなたが見てきたように、あなたはそれを上書きさせません。
class myclass(object):
@property
def age(self):
if not hasattr(self, '_age'):
self._age = self._big_long_computation()
return self._age
があり、このような__getattr__
やカスタム記述子クラスなどの他のアプローチは、ですが、この1つは簡単です - !)
ここ のデコレータです Python クックブック この問題に関しては:
class CachedAttribute(object):
''' Computes attribute value and caches it in the instance. '''
def __init__(self, method, name=None):
# record the unbound-method and the name
self.method = method
self.name = name or method.__name__
def __get__(self, inst, cls):
if inst is None:
# instance attribute accessed on class, return self
return self
# compute, cache and return the instance's attribute value
result = self.method(inst)
setattr(inst, self.name, result)
return result
はいあなたは遅延評価もしばしば記述子を使用して達成されているが、例えばを参照してください、プロパティを使用することができます:
http://blog.pythonisito.com/2008/08/lazy -descriptors.htmlする
所属していません StackOverflow