【发布时间】:2017-01-07 13:42:04
【问题描述】:
我有一个类,其中方法首先需要验证属性是否存在,否则调用函数来计算它。然后,确保属性不是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 块可能有点矫枉过正,因为这个类并没有真正与其他类交互,它只需要数据并计算一堆东西。
【问题讨论】:
-
我想你想要这样的东西:stackoverflow.com/questions/3012421/…。让一个类自己打印并不是很pythonic。改用
__repr__和/或__str__。 -
由于每个类对象都应该有
attr属性,所以最好使用一流的设计。这澄清了这个类的属性是什么。您也可以将 attr 设置为类属性,每当您使用 self.attr 访问时,它都会吞下 attr 的副本,您也可以只为特定对象设置/获取。
标签: python class oop scientific-computing class-attributes