[Tutor] methods vs. functions

Alan Gauld alan.gauld at btinternet.com
Tue Aug 23 01:45:22 CEST 2011

On 23/08/11 00:10, Robert Sjoblom wrote:
>> Can someone please explain the difference between methods and functions?

I'm sure if you go to Wikipedia you will get the correct computer 
science distinctions, however in practical terms and limiting the 
discussion to Python:

> A function is a piece of code that is called by name. It can be passed
> data to operate on (ie. the parameters) and can optionally return data
> (the return value).

That's about right, except that both theoretically and in Python there 
is always a return value. If you don't specify it Python returns a 
default value of None. (In other languages a "function" that does not 
return a value is more correctly called a procedure)

> All data that is passed to a function is explicitly passed.

That depends on how you define "passed to".
A function has visibility of the data in its surrounding
scope too. So

x = 42
def f():
    print x


will print 42 because x is implicitly passed to f() by virtue
of being in the enclosing scope.

> A method is a piece of code that is called by name that is associated
> with an object. In most respects it is identical to a function except
> for two key differences.
>      It is implicitly passed the object for which it was called

Correct. A method is a function defined inside a class.
It is the function that the class calls on receipt of
a message passed to an object. It is therefore the method
by which the object fulfils the message request, hence the
name "method".

>      It is able to operate on data that is contained within the class
> (remembering that an object is an instance of a class - the class is
> the definition, the object is an instance of that data)

That's more complicated. It can operate on data within the object by 
using the object reference passed to it. It can operate on data within 
the class (ie. class data not instance data) by reference to the class
in which it is defined. But in Python, unlike other languages, there is 
no "magic" visibility of these data attributes, it all happens via very 
explicit references.

Perhaps more important is that methods are part of the class heirarchy 
lookup mechanism. Thus a method may be executed by an object of another 
class if the other class inherits from the defining class.

class A:
    def f(self): print 'I'm in A'

class B(A): pass

a = A()
b = B()

for obj in (a,b):

Method f() gets called for both objects even though it is only defined
in class A.


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list