Let me illustrate with an example.
Say I want to create a class Returns
that generates the returns of a stock for example. Returns can be arithmetic or logarithmic, and I want to be able to choose at instantiation which I want. For the moment, I do the following:
def arithmetic(prices):
daily_ret = []
for i rows in prices:
returns.append(prices(i)-prices(i-1))
return daily_ret
def logarithmic(prices):
daily_ret = []
for i rows in prices:
returns.append(np.ln(prices(i) / prices(i-1))
return daily_ret
class Returns:
def __init__(self, stock_ticker, return_calc=arithmetic):
self.stock_ticker = stock_ticker
self.return_calc = return_calc
def calculate_returns(self):
get_price_data_from_ticker = whatever_data_source()
if self.return_calc = 'arithmetic':
returns = arithmetic(get_price_data_from_ticker)
elif self.return_calc = 'logarithmic':
returns = logarithmic(get_price_data_from_ticker)
return returns
x = Returns('AAPL US Equity', return_calc='logarithmic')
print(x.calculate_returns())
This seems like the code is just badly written, and I'm missing something obvious because I've had the same question over and over.
Another thing that I've done is use getattr to dynamically get the name of the function or class I'll use and pass on arguments. Also another thing I've found is using globals() to dynamically create classes.
I'm wondering if there's a macro construction that I'm missing, because even if these 2 solutions above feel quite nice, it feels like there's a deeper structural issue with the code.
Language is Python 3