BruceJohnJennerLawso BruceJohnJennerLawso - 11 months ago 47
Python Question

Passing an object method to an external function in python

Ok, so the task Im trying to accomplish is a bit dense to post in full here, but Ive written an example that shows what Im trying to 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

## the real version would have a lot more methods that return the
## stats for this object

def getStatMean(doggies, statCall):
output = 0.0

for dog in doggies:
output += dog.statCall()
output /= float(len(doggies))

return output

if(__name__ == "__main__"):
doggies = []
for i in range(0, 100):
doggies.append(Dog(10, 20, 30, random.random()*10))

print getStatMean(doggies, Dog.getAge)

essentially my problem is that I have a list of objects. These objects all have a large number of stat calls that I am looking to manipulate in the same way (in this case calculate a mean, but the actual example is more complex).

The simplest way of doing this would be to write a getStatMean function for each one of the methods that the object has, but this starts to grow out of control as I add more and more methods to the object. I want to be able to pass the method name to one function, and call the method name that was passed on each object like in the example.

When I try to run the snippet posted above, I get

Traceback (most recent call last): File "", line 39, in

print getStatMean(doggies, Dog.getAge) File "", line 26, in getStatMean
output += dog.statCall() AttributeError: Dog instance has no attribute 'statCall'

Is what I am trying to do possible in python, or am I approaching this problem the wrong way?

Answer Source

FIrst of all : methods of instance are named methods because they are in fact bound function thats mean python is automatically passing to them it first param which is instance on which You call them. So if you are acessing method from class You must provide this self by yourself. And use just function without class. so call should look like this :

output += statCall(dog)