Python

Greg Kitchin
Greg Kitchin
20,883 Points

Difference between functions and methods in Python

I've just started the new Python course, and a little confused over how a function and method are different. The way they're described, they sound similar, but am I right in saying a method would be specific to an object, while a function is more generic in relation to the overall program? I'm guessing they're created in a different manner as well, but the way they're described is throwing me a little.

I've done a bit of Java, so that's where I'm coming from, but thought I better ask this.

1 Answer

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Greg;

I think you are understanding things well, but let me try.

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

def sum(num1, num2):
    return num1 + num2

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.

  1. It is implicitly passed for the object for which it was called.
  2. 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).
class Dog:
    def my_method(self):
        print "I am a Dog"

dog = Dog()
dog.my_method()  # Prints "I am a Dog"

(this is a simplified explanation, ignoring issues of scope etc.)

Post back if you still have questions.

Happy coding,
Ken