我有一个类,其中一个方法首先需要验证一个属性是否存在,否则调用一个函数来计算它。然后,确保该属性不是 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
block 可能有点矫枉过正,因为这个类并没有真正与其他类交互,它只需要数据和计算一堆东西。
最佳答案
首先,您可以使用hasattr
来检查对象是否具有属性,如果属性存在则返回True
。
hasattr(object, attribute) # will return True if the object has the attribute
其次,您可以在 Python 中自定义属性访问,您可以在这里阅读更多相关信息:https://docs.python.org/2/reference/datamodel.html#customizing-attribute-access
基本上,您可以重写 __getattr__
方法来实现这一点,例如:
类 myclass2(): def init( self ): 通过
def compute_attr(self):
self.attr = 1
return self.attr
def print_attribute(self):
print self.attr
def __getattr__(self, name):
if hasattr(self, name) and getattr(self, name)!=None:
return getattr(self, name):
else:
compute_method="compute_"+name;
if hasattr(self, compute_method):
return getattr(self, compute_method)()
确保你只使用 getattr
来访问 __getattr__
中的属性,否则你将以无限递归结束
关于Python设计——初始化、设置和获取类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522083/