Python What Is the Difference Between a Function and a Method

Python function vs method

The difference between a function and a method in Python is:

  1. A function is implemented outside of a class. It does not belong to an object.
  2. A method is implemented inside of a class. It belongs to an object.

Calling a function on an object looks like this:

function(object)

And calling a method of an object looks like this:

object.method()

Here is a simple illustration:

Python function vs method

Let’s see some simple examples to support understanding it better.

Function vs Method Example in Python

Probably the most famous function in Python is the print() function. You can call it on any object to output the object as a text in the console.

To print a string for example, call print() function on a string.

For example:

print("Test")

This is a great example of calling a function on an object in Python.

Let’s continue with strings.

The string type str has a ton of built-in methods. One of which is the upper() method that converts the string object into uppercase.

To convert a string into uppercase, call the upper() method of a string.

string = "Test"
upper_string = string.upper()

This is a great example of calling a method on an object in Python.

Code Example

To finish it off, here is a code example of a custom class with a method. Outside the class, there is a function with the same name.

Please read the comments to understand what it’s all about.

class Weight():
   weight = 100
   # Defining a method
   def to_pounds(self):
      return 2.205 * self.weight

# Defining a function
def to_pounds(kilos):
   return 2.205 * kilos

# Calling a method on an object.
w = Weight()
pounds = w.to_pounds()


# Calling a function on an object
kilos = 100
pounds = to_pounds(kilos)

Conclusion

Today you learned what is the difference between a function and a method in Python.

  • A function does not belong to a class. It is implemented outside of a class.
  • A method belongs to a class and it can only be called on objects of that class. A method is implemented inside of a class.

An example of a function in Python is the print() function.

An example of a commonly used method in Python is the upper() method of a string.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

Python Classes 101

Python Interview Questions

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.