在python自定义方法中有一些只读属性,一般我们用不到,但是了解下也不错,通过这篇文章,我们还可以了解到==绑定方法==和==非绑定方法==的区别。
im_self
指代类的实例对象。im_func
指代函数对象。im_class
指代绑定方法的类或者调用非绑定方法的类。__doc__
方法的文档注释__name__
方法名__module__
方法所在的模块名。__func__
等价于im_func
__self__
等价于im_self
示例如下:
class Stu(object):
def __init__(self, name):
self.name = name
def get_name(self):
"this is the doc"
return self.name
def show_attributes(method):
print "im_self=", method.im_self
print "__self__=", method.__self__
print "im_func=", method.im_func
print "__func__=", method.__func__
print "im_class=", method.im_class
print "__doc__=", method.__doc__
print "__module__=", method.__module__
print "...........bounded method........"
stu=Stu("Jim")
method = stu.get_name
show_attributes(method)
method()
print "...........unbounded method......"
method = Stu.get_name
show_attributes(method)
method()
输出结果如下:
...........bounded method.......Traceback (most recent call last):.
im_self= <__main__.Stu object at 0x0245D2B0>
__self__= <__main__.Stu object at 0x0245D2B0>
im_func= <function get_name at 0x02455830>
__func__= <function get_name at 0x02455830>
im_class= <class '__main__.Stu'>
__doc__= this is the doc
__module__= __main__
...........unbounded method......
im_self= None
__self__= None
im_func= <function get_name at 0x02455830>
__func__= <function get_name at 0x02455830>
im_class= <class '__main__.Stu'>
__doc__= this is the doc
__module__= __main__
File "E:\demo\py\demo.py", line 29, in <module>
method()
TypeError: unbound method get_name() must be called with Stu instance as first argument (got nothing instead)
从上面的输出结果可以看出,当通过类直接调用方法时,方法的im_self
与__self__
属性为None,该方法为非绑定方法(unbound method),当我们通过实例调用该方法时,方法的im_self
与__self__
属性为实例对象。这时该方法为绑定方法(bound method),但是不管哪种情况,方法的im_class
都为调用类,而im_func
为原始的函数对象。