在python自定义方法中有一些只读属性,通常咱们用不到,可是了解下也不错,经过这篇文章,咱们还能够了解到==绑定方法==和==非绑定方法==的区别。python
im_self
指代类的实例对象。函数
im_func
指代函数对象。this
im_class
指代绑定方法的类或者调用非绑定方法的类。code
__doc__
方法的文档注释对象
__name__
方法名文档
__module__
方法所在的模块名。get
__func__
等价于im_func
it
__self__
等价于im_self
io
示例以下:ast
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
为原始的函数对象。