I have a class
with many of its methods dependent on the likely, but not certain, existence of another specific instance of the class
. These methods would be conditioned along the lines of: if other_instance return X else return None
. In fact, I wrote several identical if
statements as part of the code for each method. (Also note that I cannot use a custom __init__
because of inheritance issues.) Is there a practical or appropriate approach to limiting this redundant coding other than the None
-ing out the dependent methods as I show below (on a greatly simplified model)?
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?'