I am trying to make my new code as user friendly as possible and what I would have in mind for the particular problem I am facing atm is this:
Suppose we have
import numpy as np
class TestClass:
def __init__(self, data):
self.data = data
@property
def method_a(self):
return np.median(self.data)
@property
def method_b(self):
return np.mean(self.data)
foo = TestClass([1, 2, 5, 7, 12, 6, 3, 37, 16])
print(foo.method_a)
print(foo.method_b)
Everything is fine so far. Method A gives me the median, method B the mean.
During processing I will switch depending on circumstances between both methods. So sometimes I will call method A, sometimes method B. However, what I want is then to continue with a method C, that acts upon the result of either method A or B in such a way
final_result = foo.method_a.method_c
or
final_result = foo.method_b.method_c
I know it is possible to write method C as a function and do it like this:
final_result = method_c(foo.method_a)
final_result = method_c(foo.method_b)
but I think it would make the code easier to read if I could apply method C as stated above.
Is this possible somehow?
thanks
meanandmedian, why not wrap it first before returning?method_aormethod_bwithout then callingmethod_con the result?method_aandmethod_bare returning a simple number, andmethod_cwould take that number as a parameter. Your proposed change would mean making a whole new class, or adding state toTestClass, just to enable call-chaining. You would be adding complexity to the implementation of the method, for what's a very debatable increase in readability of the call. Personally, I prefer using parameters and return values over object state whenever appropriate. The rules are a little different at API surfaces, but to make an API friendly you'd ideally only expose one method.