好吧,所以我想要完成的任务在这里完整发布有点密集,但是我写了一个例子来展示我想要做什么。
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)
本质上我的问题是我有一个对象列表。这些对象都有大量的统计调用,我希望以相同的方式进行操作(在本例中计算平均值,但实际示例更复杂)。
最简单的方法是为对象具有的每个方法编写一个 getStatMean 函数,但随着我向对象添加越来越多的方法,这种情况开始变得失控。我希望能够将方法名称传递给一个函数,并调用在每个对象上传递的方法名称,如示例中所示。
当我尝试运行上面发布的代码片段时,我得到了
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'
我试图在Python中做的事情是可能的,还是我以错误的方式解决这个问题?
最佳答案
首先:实例的方法被命名为方法,因为它们实际上是绑定(bind)函数,这意味着Python会自动将其第一个参数传递给它们,该参数是实例的实例你调用他们。因此,如果您要从类访问方法,您必须自己提供此self。 并且只使用函数而不使用类。 所以调用应该如下所示:
output += statCall(dog)
关于python - 在Python中将对象方法传递给外部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39282483/