详解python自定义方法属性

在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为原始的函数对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值