Python:传递类函数作为对外部函数的引用

Oha*_*Dan 1 python oop

我有一个具有多个函数的类。\n从该类的外部,我想通过引用指定要调用的函数 - 但我不确定如何调用。

\n

例如,我有一个Animal具有两个函数sound和 的类food。我想 \xc2\xa0 编写一个Zoo类,该类接收 \ 的函数之一Animal作为输入,并将该函数应用于它拥有的每个动物实例(函数all_animals_features)。

\n
class Animal:\n    def __init__(self, sound, food):\n        self.my_sound = sound\n        self.my_food = food\n\n    def sound(self):\n        # Do some complicated stuff....\n        return self.my_sound\n\n    def food(self):\n        return self.my_food\n\n\nclass Zoo():\n    def __init__(self, animals):\n        self.animals = animals\n\n    def all_animals_features(self, f):\n        return [animal.f() for animal in self.animals]\n\ndog = Animal(\'Woof\', \'Bone\')\ncat = Animal(\'Meow\', \'Cream\')\nzoo = Zoo([cat, dog])\nzoo.all_animals_features(Animal.sound)\n
Run Code Online (Sandbox Code Playgroud)\n

但是当然,\'Animal\' object has no attribute \'f\'

\n

知道如何实施吗?

\n
\n

澄清:如果需要的只是获取属性\xc2\xa0(如这个愚蠢的示例所示),那么使用getattr()可能会更简单。

\n

qua*_*ana 6

在您的情况下,您只需要调整该方法的调用方式:

class Zoo():
    def __init__(self, animals):
        self.animals = animals

    def all_animals_features(self, f):
        return [f(animal) for animal in self.animals]

dog = Animal('Woof', 'Bone')
cat = Animal('Meow', 'Cream')
zoo = Zoo([cat, dog])
print(zoo.all_animals_features(Animal.sound))
Run Code Online (Sandbox Code Playgroud)

输出:

['Meow', 'Woof']
Run Code Online (Sandbox Code Playgroud)

由于您提供Animal.sound, 作为参数f,列表理解中的调用是:f(animal)