题
给定一个方法的引用,有没有办法检查该方法是否绑定到一个对象?您还可以访问它绑定到的实例吗?
解决方案
def isbound(method):
return method.im_self is not None
def instance(bounded_method):
return bounded_method.im_self
通过从类中检索用户定义的函数对象创建用户定义的方法对象时
im_self
属性是None
方法对象被认为是未结合的。当一个通过从类中检索用户定义的函数对象创建一个实例时,im_self
属性是实例,方法对象被绑定。无论哪种情况,新方法的im_class
属性是检索发生的类im_func
属性是原始函数对象。
在Python中 2.6 和 3.0:
实例方法对象具有包含该方法的对象和函数的新属性;新的同义词
im_self
是__self__
, , 和im_func
也可用作__func__
. 。旧名称仍然在Python 2.6中得到支持,但以3.0倒入。
其他提示
在Python 3中 __self__
属性是 仅有的 设置绑定方法。没有设置为 None
在普通函数(或未绑定方法,只是 python 3 中的普通函数)上。
使用这样的东西:
def is_bound(m):
return hasattr(m, '__self__')
所选答案几乎在所有情况下都有效。但是,当使用所选答案检查方法是否绑定在装饰器中时,检查将失败。考虑这个示例装饰器和方法:
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
这 print
装饰器中的语句将打印 False
。在这种情况下,我找不到任何其他方法,只能使用参数名称检查函数参数并查找名为 self
. 。这也是 不是 保证完美工作,因为方法的第一个参数不强制命名 self
并且可以有任何其他名称。
import inspect
def is_bounded(function):
params = inspect.signature(function).parameters
return params.get('self', None) is not None
本人 属性 (仅限Python 2)
不隶属于 StackOverflow