The title isn’t very clear but I’ll try to explain.
Having this class:
class Wrapped(object):
def method_a(self):
# do some operations
return n
def method_b(self):
# also do some operations
return n
I want to have a class that performs the same way as this one:
class Wrapper(object):
def __init__(self):
self.ws = [Wrapped(1),Wrapped(2),Wrapped(3)]
def method_a(self):
results=[Wrapped.method_a(w) for w in self.ws]
sum_ = sum(results,0.0)
average = sum_/len(self.ws)
return average
def method_b(self):
results=[Wrapped.method_b(w) for w in self.ws]
sum_ = sum(results,0.0)
average = sum_/len(self.ws)
return average
Obviously this is not the actual problem at hand (it is not only two methods), and this code is also incomplete (only included the minimum to explain the problem).
So, what i am looking for is a way to obtain this behavior. Meaning, whichever method is called in the wrapper class, call that method for all the Wrapped class objects and return the average of their results.
Can it be done? How?
Thanks in advance.
Edit
Thanks for the answers… after seeing them the solution it all seems obvious 🙂 I have chosen Alex Martelli’s answer because it explained the solution well. The other answers where also useful, that’s why I also voted them up.
While quite doable, it’s just a little bit tricky because the getting of a method (or other attribute) and the calling thereof are separate operations. Here’s a solution:
It’s a bit simplistic (assumes no change in
self.wsbetween the getting and the calling — one could of course “snapshot”self.wsat the moment of the getting, if that’s the desired semantics; doesn’t use@functools.wrapsso doesn’t preserve the docstring &c if those need preserving), but should be mostly workable for your purposes.