我有一个具有多个函数的类。\n从该类的外部,我想通过引用指定要调用的函数 - 但我不确定如何调用。
\n例如,我有一个Animal具有两个函数sound和 的类food。我想 \xc2\xa0 编写一个Zoo类,该类接收 \ 的函数之一Animal作为输入,并将该函数应用于它拥有的每个动物实例(函数all_animals_features)。
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)\nRun Code Online (Sandbox Code Playgroud)\n但是当然,\'Animal\' object has no attribute \'f\'。
知道如何实施吗?
\n澄清:如果需要的只是获取属性\xc2\xa0(如这个愚蠢的示例所示),那么使用getattr()可能会更简单。
\n在您的情况下,您只需要调整该方法的调用方式:
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)