首先来看他们的定义,
函数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).
首先,从概念上去分。函数可以看成一个数学上的概念,比如说完成加减乘除的函数。它其实有一个内在的约束:就是如果参数相同,对一个函数的每次调用返回的结果应该始终一样。
而方法是要和对象联系起来的。而且它有一个银行的参数:就是它所作用的对象。而这些更多地是在面向对象的语境里来说。
而从Python的定义来看,它将method作为function的一种特例来处理了。但当你在文档里看到instance method object和function object的说法时,你应该了解他们的差异。
>>> class MyClass:
i = 12345
def f(self):
return "hello world"
>>> x = MyClass()
>>> x.f.__class__
>>> MyClass.f.__class__
从上面的例子可以看出,一个是method object,一个是function object。
此外,Python里面还有staticmethod和classmethod的概念,他们和普通的method又有些区别。
->classmethod将类作为第一个隐含的参数
->而staticmethod没有任何隐含的参数,有点类似于Java里的static
>>> class MyClass:
i = 12345
@staticmethod
def f(self):
return "hello world"
def add(x, y):
return x+y
@classmethod
def foo(cls):
print(cls)
>>> MyClass.f.__class__
>>> MyClass.add.__class__
>>> MyClass.foo.__class__
>>> x = MyClass()
>>> x.f.__class__
>>> x.add.__class__
>>> x.foo.__class__
>>> x.foo()
当然,在很多语言里,这两者的区别没那么明显。