function,method的区别, unbound method 和 bound method的区别

function 和 method区别

python层表现上
function : A series of statements which returns some value toa caller. It can also be passed zero or more arguments which may beused in the execution of the body.就是声明的一个函数

method : A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which isusually called self).就是function和类关联在一起了, bound method 和 unbound method都是如此

源码上
function, 可以看到, 就是code 和 globals, 就是代码 和 globals中的变量( 也就是执行环境 )

在这里插入图片描述

method, 是PyFunctionObject 和 一个实例 (这里是python3源码, python2里第二个参数应该是kclass)
在这里插入图片描述

unbound method 和 bound method 的区别

更详细的虚拟机层面的解释, 可以看
Python: 函数与方法的区别 以及 Bound Method 和 Unbound Method
这里是python2的概念,
unbound method: 没有绑定实例的method
bound method: 绑定实例的method
python 2.7.18环境下

class Test(object):


	def f(self):
		pass



a = Test()
print a.f
print a.f.im_self
print Test.f
print Test.f.im_self

执行结果
在这里插入图片描述
可以看到, bound method的im_self就是实例, 而unbound method的im_self是None

python3环境下

import inspect

class Test(object):


	def f(self):
		pass



a = Test()
print(a.f)
print(getattr(a.f, 'im_self', None))
print(Test.f)
print(getattr(Test.f, 'im_self', None))
print(inspect.isfunction(Test.f))

执行结果, 我们发现Test.f变成function了, 而非unbound method, 并且im_self这个参数消失了
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值