8.3 Instance, Class & Static Methods
We explore the three types of methods: instance methods for object behavior, class methods for class operations, and static methods for utility functions.
In Python, methods within a class can be of three different types, depending on the first argument they accept and their intended use.
Instance Methods
This is the most common type of method. Their first argument is always `self`, which refers to the specific instance. They are used to access or modify the state (attributes) of the instance. Example: a `deposit()` method in a `BankAccount` class would modify `self.balance`.
Class Methods
They are declared using the `@classmethod` decorator. Their first argument is not `self` but `cls`, which refers to the class itself. They operate on the class attributes rather than the instance attributes. They are often useful as alternative constructors, i.e., ways to create an object from different kinds of data (e.g., creating a `Date` object from a string instead of three numbers).
Static Methods
They are declared with the `@staticmethod` decorator. They accept neither `self` nor `cls` as their first argument. They are essentially regular functions that "live" inside the class's namespace, usually because they have a logical connection to it, but do not depend on either the instance state or the class state. They are useful as utility functions.
class MathUtils:
@staticmethod
def is_even(number):
"""Static method: Checks if a number is even."""
return number % 2 == 0
# Calling a static method without creating an instance
print(f"Is 10 even? {MathUtils.is_even(10)}")
Practical Exercises
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.