给定对方法的引用,是否有办法检查该方法是否绑定到对象? 您还可以访问绑定到的实例吗?
1 2 3 4 5
| def isbound(method):
return method.im_self is not None
def instance(bounded_method):
return bounded_method.im_self |
用户定义的方法:
When a user-defined method object is
created by retrieving a user-defined
function object from a class, its
im_self attribute is None and the
method object is said to be unbound.
When one is created by retrieving a
user-defined function object from a
class via one of its instances, its
im_self attribute is the instance, and
the method object is said to be bound.
In either case, the new method's
im_class attribute is the class from
which the retrieval takes place, and
its im_func attribute is the original
function object.
在Python 2.6和3.0中:
Instance method objects have new
attributes for the object and function
comprising the method; the new synonym
for im_self is __self__, and im_func
is also available as __func__. The old
names are still supported in Python
2.6, but are gone in 3.0.
在python 3中,__self__属性仅在绑定方法上设置。 在普通函数(或未绑定方法,在python 3中只是普通函数)中,未将其设置为None。
使用这样的东西:
1 2
| def is_bound(m):
return hasattr(m, '__self__') |
所选答案几乎在所有情况下均有效。 但是,当使用选择的答案检查方法是否绑定到装饰器中时,检查将失败。 考虑以下示例装饰器和方法:
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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并且可以具有任何其他名称。
1 2 3 4 5
| import inspect
def is_bounded(function):
params = inspect.signature(function).parameters
return params.get('self', None) is not None |
im_self属性(仅Python 2)