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
这个参数消失了