方法是以类实例作为其第一个参数的函数。方法是类的成员。class C:
def method(self, possibly, other, arguments):
pass # do something here
因为您想知道它在Python中的具体含义,所以可以区分绑定方法和未绑定方法。在Python中,所有函数(以及方法)都是可以传递和“播放”的对象。因此,unbound方法和bound方法的区别是:
1)绑定方法# Create an instance of C and call method()
instance = C()
print instance.method # prints '>'
instance.method(1, 2, 3) # normal method call
f = instance.method
f(1, 2, 3) # method call without using the variable 'instance' explicitly
绑定方法是属于类实例的方法。在本例中,instance.method绑定到名为instance的实例。每次调用绑定方法时,都会自动将实例作为第一个参数传递,按照惯例称为self。
2)解除绑定的方法print C.method # prints ''
instance = C()
C.method(instance, 1, 2, 3) # this call is the same as...
f = C.method
f(instance, 1, 2, 3) # ..this one...
instance.method(1, 2, 3) # and the same as calling the bound method as you would usually do
当您访问C.method(类中的方法而不是实例中的方法)时,会得到一个未绑定的方法。如果要调用它,则必须将实例作为第一个参数传递,因为该方法绑定到任何实例时都是而不是。
知道这一区别后,您可以将函数/方法用作对象,就像传递方法一样。作为一个示例用例,假设一个API允许您定义回调函数,但是您希望提供一个方法作为回调函数。没问题,只要把self.myCallbackMethod作为回调传递,它就会自动被调用,实例作为第一个参数。在C++等静态语言中(或者只使用欺骗),这是不可能的。
希望你明白我的意思;)我想这就是你应该知道的方法基础知识。您还可以阅读更多关于classmethod和staticmethod装饰器的内容,但这是另一个主题。