Function vs Method in Python: Key Differences and Usage
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.
| Aspect | Function | Method |
|---|---|---|
| Definition | Independent block of code | Function bound to an object |
| Call syntax | func() | obj.method() |
| First argument | Explicitly passed if needed | Automatically receives self (the object) |
| Belongs to | Module or global scope | Class or object instance |
| Usage | General purpose tasks | Operate on object data |
| Example | def 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.
def greet(name): print(f"Hello, {name}!") greet("Alice")
Method Equivalent
This example shows a method inside a class that prints a greeting message using the object's attribute.
class Greeter: def __init__(self, name): self.name = name def greet(self): print(f"Hello, {self.name}!") person = Greeter("Alice") person.greet()
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.