你如何检查是否绑定了python方法?

Rea*_*nly 33 python python-datamodel

给定方法的引用,有没有办法检查方法是否绑定到对象?你还可以访问它绑定的实例吗?

jfs*_*jfs 39

def isbound(method):
    return method.im_self is not None

def instance(bounded_method):
    return bounded_method.im_self
Run Code Online (Sandbox Code Playgroud)

用户定义的方法:

通过从类中检索用户定义的函数对象来创建用户定义的方法对象时,其 im_self属性为None,并且方法对象被称为未绑定.当通过其实例之一从类中检索用户定义的函数对象来创建一个时,其 im_self属性是实例,并且方法对象被称为绑定.在任何一种情况下,新方法的 im_class属性都是从中进行检索的类,其im_func属性是原始函数对象.

在Python 2.6和3.0中:

实例方法对象具有包含该方法的对象和函数的新属性; im_selfis 的新同义词__self__,im_func 也可用作__func__.Python 2.6仍然支持旧名称,但在3.0中已经消失了.


Rob*_*gar 18

在python 3中,__self__属性在绑定方法上设置.它没有设置为None普通函数(或非绑定方法,它们只是python 3中的普通函数).

使用这样的东西:

def is_bound(m):
    return hasattr(m, '__self__')
Run Code Online (Sandbox Code Playgroud)


Kla*_*aus 5

选择的答案几乎在所有情况下均有效。但是,当使用选择的答案检查方法是否绑定到装饰器中时,检查将失败。考虑以下示例装饰器和方法:

def my_decorator(*decorator_args, **decorator_kwargs):
    def decorate(f):
        print(hasattr(f, '__self__'))
        @wraps(f)
        def wrap(*args, **kwargs):
            return f(*args, **kwargs)
        return wrap
    return decorate

class test_class(object):
    @my_decorator()
    def test_method(self, *some_params):
        pass
Run Code Online (Sandbox Code Playgroud)

print装饰器中的语句将打印False。在这种情况下,我只能找到其他方法,只能使用其参数名称来检查函数参数,并查找一个名为的函数self。这也不保证可以正常工作,因为方法的第一个参数不会被强制命名,self并且可以具有任何其他名称。

import inspect

def is_bounded(function):
    params = inspect.signature(function).parameters
    return params.get('self', None) is not None
Run Code Online (Sandbox Code Playgroud)

  • 好吧,“f”实际上从未绑定到“test_class”,这就是这里的复杂之处。甚至 `decorate` 也没有绑定(您可以通过检查 test_class.test_method !=decorate 来验证)。绑定方法是从“decorate”创建的,并且 *that* 是附加到“test_class”的方法。您真正想要查找的是是否已从特定函数创建了绑定方法。我不确定这是否可能 (2认同)