实例方法的__func__属性的理解

先摆一段代码:

class A:
    def foo(self): 
            pass
    bar = foo
1
2
3
4
明确一个概念:

method 是一种 function,method 有一个__func__ 属性,指向一个 function。
1
A().foo 即为第一种方法创建的 method,A().bar 则为第二种。那段话的意思是: A().bar.__func__ 不是指向 A().foo,而是指向 A().foo.__func__。

class(object, instance) 中的 function 我们称为 method,而一個 method 是一个bound (绑定的) function,绑定是什么呢? 自然是绑定 instance.
我们看下面这个案例Test class:

class Test:

    def __init__(self):
        self.name = 'hello'

    def func(self):
        return self.name
1
2
3
4
5
6
7
它有一个method func,如果我们使用该类产生实例 test1 和 test2:

>>> test1 = Test()
>>> test2 = Test()
>>> test1.func
<bound method Test.func of <test.Test object at 0x7f15d0703eb8>>
1
2
3
4
我们会发现 test1.func 是一个 bound method,这代表了它与 test1 绑定,这个绑定最重要的一点就是 test1.func 的 self 属性是 test1.

这看起来很 trivial,不过这中间有个很重要的概念,就是一个 class 中的某个 method 其实只有一个实体,也就是无论我们用 Test 产生了多少个instances,它们都是共用同一个 function func,但是每个 instance 都会有一个将func 绑定到自己的 bound method func,那我们要如何观察到真正的(unbound) function呢? 很简单,这个真正的 function object 被记录在 bound method 的 func 属性:

>>> test1.func # instance 中的 func
<bound method Test.func of <test.Test object at 0x7f15d0703eb8>>
>>> test2.func # instance 中的 func
<bound method Test.func of <test.Test object at 0x7f15d0703320>>
>>> test1.func.__func__ # unbound function
<function Test.func at 0x7f15d0671048>
>>> test2.func.__func__ # unbound function
<function Test.func at 0x7f15d0671048>
>>> Test.func # unbound function
<function Test.func at 0x7f15d0671048>
>>> test1.func.__func__ is test2.func.__func__
True
1
2
3
4
5
6
7
8
9
10
11
12
由上可知,虽然每个 instance 有自己的 bound method,但这些其实只是将原本的 function 绑定了不同的 instance 后所产生的 functions.


--------------------- 
作者:Never-Giveup 
来源:CSDN 
原文:https://blog.csdn.net/qq_36653505/article/details/84994570 
版权声明:本文为博主原创文章,转载请附上博文链接!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值