我有多个使用单个变量的函数,这个变量的计算代价很高,所以我不想重复这个。我有两个简单的方法来做到这一点,并想知道你觉得哪种方法更“pythonic”或更好的方法。哪种方法最为Pythonic?处理变量是否存在
class A:
def __init__(self):
self.hasAttr = False
def compute_attr(self):
self.attr = 10
self.hasAttr = True #for func2 only
def func1(self):
try:
print self.attr == 10
except AttributeError:
self.compute_attr()
self.func1()
def func2(self):
if not self.hasAttr: self.compute_attr()
print self.attr == 10
a = A()
a.func1()
a.func2()
func1使用一个简单的尝试,除了捕获AttributeError并在这种情况下计算属性。 func2使用存储的布尔值来检查计算是否已完成。
是否有任何理由,一种方法会比另一种方法更受欢迎?此外,在func2中定义一个做检查的装饰器会有什么意义吗?
感谢您的任何帮助。
注意,Python有一个内置的'hasattr' –
有[一个更好的方法(http://stackoverflow.com/questions/3012421 /蟒蛇-memoising递延查对财产装饰)。 –
可能重复的[Python - 延迟加载类属性](http://stackoverflow.com/questions/17486104/python-lazy-loading-of-class-attributes) –