我有一个class
,其许多方法依赖于class
的另一个特定实例的可能但不确定的存在。这些方法将按照以下方式进行调整:if other_instance return X else return None
。事实上,我写了几个相同的if
语句作为每个方法的代码的一部分。 (另请注意,由于继承问题,我无法使用自定义__init__
。)是否有一种实用或适当的方法来限制除None
之外的冗余编码 - 如下所示 - 依赖方法(在一个大大简化的模型上)?
class QuarterResult(ParentClass):
result = None
prior = None
def get_prior_quarter(self):
# code to find prior_quarter
if prior_quarter:
self.prior = prior_quarter
return prior_quarter
# commence None-ing out unusable methods
# Note: the actual model has 10+ methods which need prior
unusable_methods = ('change_in_results', 'quarterly_return')
for mthd in unusable_methods:
setattr(self, mthd, None)
# assume this method is ALWAYS run first
def calculate_result(self, *args):
# result = some calculation based on the given args
_ = self.get_prior_quarter()
self.result = result
@property
def change_in_results(self):
return self.prior.result - self.result
@property
def quarterly_return(self):
return self.change_in_results / self.prior.results
@property
def real_result(self):
if self.result == 42:
return "You are right: it's 42"
else:
return 'What do I know?'
答案 0 :(得分:5)
您可以使用自定义装饰器
def dependent(meth):
def depmeth(self, *args, **kwargs):
if self.other_instance:
return meth(self, *args, **kwargs)
else:
return None
return depmeth
然后你的班级将成为
class ...:
...
def meth1(self, x):
return "always working"
@dependent
def meth2(self, y):
return "code executed only if other_instance is present"