如何检查python方法是否绑定?
时间:2020-03-05 18:50:27 来源:igfitidea点击:
给定对方法的引用,是否有办法检查该方法是否绑定到对象?我们还可以访问绑定到的实例吗?
解决方案
回答
im_self属性(仅Python 2)
回答
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.