[Tutor] methods vs. functions

Modulok modulok at gmail.com
Tue Aug 23 00:51:10 CEST 2011

On 8/22/11, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote:
> Steven D'Aprano wrote:
>>(Methods are very similar to functions. At the most basic level, we can
>>pretend that a method is just a function that comes stuck to something
>>else. Don't worry about methods for now.)
> Can someone please explain the difference between methods and functions?
> Thanks,
> Ramit

At the most basic level, they're the same. If you have a named, stand-alone
section of code that (optionally) operates on some argument passed to it, it's
called a function. If you have the same exact code, but you group it together
into a named unit along with the data it (optionally) operates on, it's called
a method. Technically in Python, they're both objects, both callables and can
be called in similar ways. The distinction is quite minimal. Here's a few

# A function that expects the first argument to be some object it operates on.
# This is just like a method, except it hasn't been declared within any class.
# Therefore, it's called a function:

def setx(foo):
    foo.x = 1

# The same exact thing again, but declared in a 'Bar' class. Now it's
# called a method. Normally the first parameter to every instance method is
# named 'self', (A convention you should adhere to.) To make this example
# clearer, however, I use the name 'foo' instead just like the last example:

class Bar(object):
    def setx(foo):
        foo.x = 1

The call itself is a little different:

    # As a function you must pass the arguments:

    a = Bar()
    setx(a)     #<-- Explicitly pass the object as an argument.

    # As a method the first argument is implied:

    a = Bar()
    a.setx()    #<-- First argument is passed automatically for you.

That said, you could also call a method as if it were a function living in the
Bar namespace:

    a = Bar()

You can even declare a function within a class that *doesn't* operate on any
instance of the class. Just like an ordinary function, you must pass all
arguments. This is called a static method and is declared with the
'@staticmethod' decorator:

    class Baz(object):
        def bonzo(x, y):
            return x+y

You can then call it like this:

    Baz.bonzo(3, 5)

This looks remarably similar to calling a function that exists in some
namespace. For example:

    import random
    random.randrange(3, 5)

So the ultimate difference? Pretty much just where you declare it. If it's in a
class it's called a method, outside of a class its called a function.
Especially in python - the distinction is small.


More information about the Tutor mailing list