我有一个类,在其中一个方法需要首先验证属性是否存在,否则调用函数计算它。然后,确保该属性不是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
块可能有点过度,因为这个类实际上并不与其他类进行交互,它只接受数据并计算一堆东西。
attr
,因此最好使用第一类设计。这样可以澄清这个类的属性是什么。您也可以将attr设置为类属性,每当您使用self.attr访问时,它将吞噬attr的副本,并且您也可以为特定对象设置/获取。 - Roshan