ok, task im trying accomplish bit dense post in full here, ive written example shows im trying do.
import random class dog: def __init__(self, height, weight, length, age): self.height = height self.weight = weight self.length = length self.age = age def getage(self): return self.age ## real version have lot more methods return ## stats object def getstatmean(doggies, statcall): output = 0.0 dog in doggies: output += dog.statcall() output /= float(len(doggies)) return output if(__name__ == "__main__"): doggies = [] in range(0, 100): doggies.append(dog(10, 20, 30, random.random()*10)) print getstatmean(doggies, dog.getage)
essentially problem have list of objects. these objects have large number of stat calls looking manipulate in same way (in case calculate mean, actual example more complex).
the simplest way of doing write getstatmean function each 1 of methods object has, starts grow out of control add more , more methods object. want able pass method name 1 function, , call method name passed on each object in example.
when try run snippet posted above, get
traceback (most recent call last): file "example.py", line 39, in print getstatmean(doggies, dog.getage) file "example.py", line 26, in getstatmean output += dog.statcall() attributeerror: dog instance has no attribute 'statcall'
is trying possible in python, or approaching problem wrong way?
first of : methods of instance named methods because in fact bound function thats mean python automatically passing them first param instance on call them. if acessing method class must provide self yourself. , use function without class. call should :
output += statcall(dog)
Comments
Post a Comment