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