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

如何编写函数生成类实例的方法名-方法映射字典

生成类实例方法名与绑定方法的映射字典

正确实现方案

要动态生成方法名字符串到绑定实例方法的映射,你需要用getattr()函数通过方法名动态获取实例上的绑定方法,修正后的生成器函数如下:

def my_method_generator(instance):
    return {
        method_name: getattr(instance, method_name)
        for method_name in dir(instance)
        if not method_name.startswith("__") and callable(getattr(instance, method_name))
    }

代码说明

  • dir(instance)返回实例所有属性和方法的名字符串列表
  • startswith("__")过滤掉Python内置的魔法方法(比如__init__、__str__)
  • callable(...)确保只保留可调用的方法,排除实例的普通属性

错误代码分析

你尝试的第二段代码报错AttributeError: 'cls' object has no attribute 'method',原因是cls.method是直接访问名为method的固定属性,而非循环中当前method变量对应的方法名。动态通过变量名获取属性必须使用getattr(),不能用点语法。

测试验证

用你的示例类测试:

class MyClass:
    def myFunc1(self, param1=None):
        return "myFunc1 called"
    def myFunc2(self, param2=None):
        return "myFunc2 called"

mycls = MyClass()
my_class_method_dict = my_method_generator(mycls)

# 调用方法
print(my_class_method_dict['myFunc1']())  # 输出: myFunc1 called
print(my_class_method_dict['myFunc2']())  # 输出: myFunc2 called

补充说明

你提到的第一段代码存在隐性问题:dir(instance)返回的是字符串,所以字典的value会是方法名字符串而非实际的方法绑定对象,无法直接调用。必须用getattr()获取真正的可调用方法对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 08:30:00