0
0
PythonComparisonBeginner · 3 min read

Function vs Method in Python: Key Differences and Usage

In Python, a function is a reusable block of code defined independently, while a method is a function that belongs to an object and is called on that object. Methods implicitly receive the object they belong to as the first argument, usually named self.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of functions and methods in Python.

AspectFunctionMethod
DefinitionIndependent block of codeFunction bound to an object
Call syntaxfunc()obj.method()
First argumentExplicitly passed if neededAutomatically receives self (the object)
Belongs toModule or global scopeClass or object instance
UsageGeneral purpose tasksOperate on object data
Exampledef greet():def greet(self):
⚖️

Key Differences

A function in Python is a block of code designed to perform a specific task and can be called anywhere after it is defined. It does not depend on any object and does not have access to object attributes unless explicitly passed. Functions are defined using the def keyword and can take any number of arguments.

A method is a function that is associated with an object, typically defined inside a class. When you call a method on an object, Python automatically passes the object itself as the first argument, conventionally named self. This allows the method to access or modify the object's attributes and other methods.

In short, methods are functions that operate on data contained within an object, while functions are standalone and do not have implicit access to object data.

⚖️

Code Comparison

This example shows a function that prints a greeting message.

python
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
Output
Hello, Alice!
↔️

Method Equivalent

This example shows a method inside a class that prints a greeting message using the object's attribute.

python
class Greeter:
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        print(f"Hello, {self.name}!")

person = Greeter("Alice")
person.greet()
Output
Hello, Alice!
🎯

When to Use Which

Choose a function when you need a reusable piece of code that does not depend on object data or state. Functions are great for general tasks like calculations or utilities.

Choose a method when you want to operate on data that belongs to an object or class. Methods help organize code related to specific objects and allow easy access to their attributes.

Key Takeaways

Functions are independent blocks of code, methods belong to objects.
Methods automatically receive the object as the first argument (self).
Use functions for general tasks, methods to work with object data.
Methods are defined inside classes, functions can be defined anywhere.
Calling syntax differs: functions use func(), methods use obj.method().