在 Python 3 中检测类(而不是实例)中的绑定方法

Her*_*nan 4 python methods function introspection

C给定一个具有 function 或 method 的类f,我使用inspect.ismethod(obj.f)(whereobj是 的实例C) 来确定是否f是绑定方法。有没有办法直接在类级别执行相同的操作(无需创建对象)?

spect.ismmethod 不起作用,如下所示:

class C(object):

    @staticmethod
    def st(x):
        pass

    def me(self):
        pass

obj = C()
Run Code Online (Sandbox Code Playgroud)

结果如下(在 Python 3 中):

>>> inspect.ismethod(C.st) 
False
>>> inspect.ismethod(C.me)
False
>>> inspect.ismethod(obj.st) 
False
>>> inspect.ismethod(obj.me)
True
Run Code Online (Sandbox Code Playgroud)

我想我需要检查函数/方法是否是类的成员而不是静态的,但我无法轻松做到这一点。我想可以使用classify_class_attrs如下所示的方法 来完成:How will you recognize where every property and method of a Python class is generated? 但我希望有另一种更直接的方式。

Mar*_*ers 5

Python 3 中没有未绑定的方法,因此您也无法检测到它们。您所拥有的只是常规功能。最多你可以看到它们是否有一个带点的限定名称,表明它们是嵌套的,并且它们的第一个参数名称是self

if '.' in method.__qualname__ and inspect.getargspec(method).args[0] == 'self':
    # regular method. *Probably*
Run Code Online (Sandbox Code Playgroud)

当然,对于恰好作为self第一个参数的静态方法和嵌套函数,以及不用作self第一个参数的常规方法(违背惯例),这当然完全失败。

对于静态方法和类方法,您必须查看类字典

>>> isinstance(vars(C)['st'], staticmethod)
True
Run Code Online (Sandbox Code Playgroud)

那是因为是在绑定到 classC.__dict__['st']之前的实际staticmethod实例。