As a self-proclaimed Pythonista, I would prefer using the property
decorator in this situation:
class A:
def __init__(self, x):
self.x = x
@property
def y(self):
if not hasattr(self, '_y'):
self._y = big_scary_function(self.x)
return self._y
def z(self, i):
return nice_easy_function(self.y, i)
Here self._y
is also lazy evaluated. The property
allows you to refer to self.x
and self.y
on the same footing. That is, when working with an instance of the class, you treat both x
and y
as attributes, even though y
is written as a method.
I've also used not hasattr(self, '_y')
instead of self._y is None
, which allows me to skip the self.y = None
declaration in __init__
. You can of course use your method here and still go with the property
decorator.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…