python, wrapping class returning the average of the wrapped members
Posted
by João Portela
on Stack Overflow
See other posts from Stack Overflow
or by João Portela
Published on 2010-03-21T23:02:25Z
Indexed on
2010/03/21
23:21 UTC
Read the original article
Hit count: 345
python
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 wan't 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.
ps-didn't know which tags to include...
© Stack Overflow or respective owner