A method is a function that takes a class instance as its first parameter. Methods are members of classes.
class C:
def method(self, possibly, other, arguments):
pass # do something here
As you wanted to know what it specifically means in Python, one can distinguish between bound and unbound methods. In Python, all functions (and as such also methods) are objects which can be passed around and "played with". So the difference between unbound and bound methods is:
1) Bound methods
# Create an instance of C and call method()
instance = C()
print instance.method # prints '<bound method C.method of <__main__.C instance at 0x00FC50F8>>'
instance.method(1, 2, 3) # normal method call
f = instance.method
f(1, 2, 3) # method call without using the variable 'instance' explicitly
Bound methods are methods that belong to instances of a class. In this example, instance.method
is bound to the instance called instance
. Everytime that bound method is called, the instance is passed as first parameter automagically - which is called self
by convention.
2) Unbound methods
print C.method # prints '<unbound method C.method>'
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
When you access C.method
(the method inside a class instead of inside an instance), you get an unbound method. If you want to call it, you have to pass the instance as first parameter because the method is not bound to any instance.
Knowing that difference, you can make use of functions/methods as objects, like passing methods around. As an example use case, imagine an API that lets you define a callback function, but you want to provide a method as callback function. No problem, just pass self.myCallbackMethod
as the callback and it will automatically be called with the instance as first argument. This wouldn't be possible in static languages like C++ (or only with trickery).
Hope you got the point ;) I think that is all you should know about method basics. You could also read more about the classmethod
and staticmethod
decorators, but that's another topic.