In Python, the difference between a function and a method mainly comes down to how they are associated with objects. Understanding this distinction is important when working with object-oriented programming, and I often apply it when designing classes and using built-in types.
- Function: A function is a standalone block of code that performs a task. It is not tied to any object and can be called independently. Functions are defined using the
defkeyword (orlambdafor anonymous functions).
Example:
def add(a, b):
return a + b
result = add(5, 3) # 8
Method: A method is a function that is associated with an object and is called on that object. Methods can access or modify the internal state of the object. For example, strings, lists, dictionaries, and custom classes all have methods.
Example:
my_list = [1, 2, 3]
my_list.append(4) # append() is a method of list
print(my_list) # [1, 2, 3, 4]
Key differences I’ve noticed in practice:
- Methods always have access to the object they belong to via
selfin instance methods. Functions do not. - Functions can exist outside of classes, whereas methods are always tied to a class or an object.
- Methods can be instance methods, class methods (
@classmethod), or static methods (@staticmethod) depending on how they interact with the object or class.
Challenges: When designing classes, I’ve occasionally confused when to use a function versus a method. I learned that if the operation depends on the object’s state, it should be a method; otherwise, it can remain a standalone function.
Limitations: Methods require an instance (except class/static methods), so they cannot be called without the object unless specifically designed. Functions are more flexible but don’t have automatic access to object data.
In practice, I use functions for general-purpose utilities and methods for operations tied to a class or object, which keeps code organized, modular, and object-oriented.
