詳解python自定義方法屬性

在python自定義方法中有一些只讀屬性,通常咱們用不到,可是瞭解下也不錯,經過這篇文章,咱們還能夠了解到==綁定方法==和==非綁定方法==的區別。python

  • im_self 指代類的實例對象。函數

  • im_func 指代函數對象。this

  • im_class 指代綁定方法的類或者調用非綁定方法的類。code

  • __doc__ 方法的文檔註釋對象

  • __name__ 方法名文檔

  • __module__ 方法所在的模塊名。get

  • __func__ 等價於im_funcit

  • __self__ 等價於im_selfio

示例以下: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爲原始的函數對象。

相關文章
相關標籤/搜索