函数与方法的区别 / Distinction of Function and Method
关于函数与方法的区别,可根据两者的定义看出,
函数function -- A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used 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 is usually called self).
从定义上来看,可以说,方法是一种依赖于类对象的特殊函数。
1 class Foo(): 2 def foo(self): 3 pass 4 print(type(Foo().foo)) 5 print(type(Foo.foo)) 6 # print(Foo().foo.__class__) 7 # print(Foo.foo.__class__)
从输出中可以看出,脱离了类实例的方法依旧是函数(此处的 type 等价于调用了内置的 __class__ 函数)。
<class 'method'> <class 'function'>