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

Python中如何判断方法对象属于指定类且无需知晓方法名

判断方法对象是否属于指定类的实现

不需要传入方法名字符串,直接通过Python方法对象的内置属性即可完成判断,具体实现如下:

核心实现代码

import inspect

def ismethod(method, target_cls) -> bool:
    # 过滤非函数/方法类型的对象
    if not inspect.isroutine(method):
        return False
    
    # 处理绑定到实例的方法(即日常通过实例调用生成的方法对象,比如示例里的f.bar)
    if inspect.ismethod(method):
        # 绑定方法自带__self__属性,指向触发方法的实例
        # 若要严格排除继承来的方法,将isinstance替换为 type(method.__self__) is target_cls
        return isinstance(method.__self__, target_cls)
    
    # 处理直接从类上获取的未绑定方法、静态方法、类方法
    # 通过__qualname__读取方法定义时所属的类名,配合属性校验避免跨类同名方法误判
    method_owner = getattr(method, "__qualname__", "").split(".")[0]
    return method_owner == target_cls.__name__ and hasattr(target_cls, method.__name__)

测试验证

对应给出的示例,运行结果符合预期:

class Foo:
    def bar(self):
        return 

f = Foo()
print(ismethod(f.bar, Foo))  # 输出 True

注意事项

  • 禁止直接通过方法名字符串做匹配,不同类下的同名方法会导致判断失效,读取方法对象内置属性的方案可靠性最高。
  • 默认逻辑会将子类继承自父类的方法判定为属于父类,如果需要严格判断方法是否直接定义在目标类中,将绑定方法判断逻辑里的isinstance(method.__self__, target_cls)替换为type(method.__self__) is target_cls即可。
  • 上述实现同时覆盖普通实例方法、类方法、静态方法的判断场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 01:06:29