You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python类方法作为引用传入外部类的函数中?

解决Zoo类调用Animal实例指定方法的问题

你遇到的'Animal' object has no attribute 'f'错误,原因是代码里的animal.f()试图访问Animal实例的f属性,但实际上你传入的f是Animal.sound这类类方法对象,实例本身并没有名为f的属性,所以报错。

下面是两种可行的修正方案:

方案1:直接调用传入的方法并传入实例参数

类方法(未绑定方法)需要接收实例作为第一个参数,直接把Animal实例传给传入的方法即可,这是最直接的写法:

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

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

完整运行代码:

class Animal:
    def __init__(self, sound, food):
        self.my_sound = sound
        self.my_food = food

    def sound(self):
        # Do some complicated stuff....
        return self.my_sound

    def food(self):
        return self.my_food


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))  # 输出: ['Meow', 'Woof']
print(zoo.all_animals_features(Animal.food))   # 输出: ['Cream', 'Bone']

方案2:通过getattr获取实例的对应方法

如果需要兼容传入方法名字符串的场景(比如传入'sound'而不是Animal.sound),可以用getattr来获取实例的方法再调用:

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

    def all_animals_features(self, f):
        # 处理传入方法对象或方法名字符串两种情况
        method_name = f.__name__ if callable(f) else f
        return [getattr(animal, method_name)() for animal in self.animals]

# 调用方式既可以传方法对象,也可以传字符串
zoo.all_animals_features(Animal.sound)
zoo.all_animals_features('food')

补充说明

如果你的需求只是单纯获取实例属性(不需要执行方法逻辑),直接用getattr会更简便:

class Zoo():
    # ...其他代码...
    def all_animals_attributes(self, attr_name):
        return [getattr(animal, attr_name) for animal in self.animals]

# 调用时传入属性名
zoo.all_animals_attributes('my_sound')  # 输出: ['Meow', 'Woof']

内容的提问来源于stack exchange,提问作者Ohad Dan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:45:41