我有一个类,其中一个方法首先需要验证一个属性是否存在,否则调用一个函数来计算它。然后,确保该属性不是None
,它对它执行一些操作。我可以看到两种略有不同的设计选择:
class myclass():
def __init__(self):
self.attr = None
def compute_attribute(self):
self.attr = 1
def print_attribute(self):
if self.attr is None:
self.compute_attribute()
print self.attr
和
class myclass2():
def __init__(self):
pass
def compute_attribute(self):
self.attr = 1
return self.attr
def print_attribute(self):
try:
attr = self.attr
except AttributeError:
attr = self.compute_attribute()
if attr is not None:
print attr
在第一个设计中,我需要确保None
预先设置好所有的类属性,这样可以变得冗长但也可以明确对象的结构。
第二种选择似乎是使用更广泛的一种。但是,出于我的目的(与信息论相关的科学计算)try except
,考虑到这个类并没有真正与其他类交互,它只需要数据并计算一堆东西,因此在任何地方使用块可能有点过头了。