Understanding Python Methods: Instance, Class, and Static Methods
While exploring Python code in software engineering and AI development, I came across the @staticmethod decorator.
At first, I wondered why some methods inside a class require self, while others do not.
This led me to explore three different types of methods in Python:
- Instance methods
- Class methods
- Static methods
Although they are all defined inside a class, they serve different purposes and have different access to object and class state.
1. Understanding Classes and Instances
Before discussing different types of methods, it is important to understand the difference between a class and an instance.
1
2
3
class Train:
def __init__(self, scheduled):
self.scheduled = scheduled
A class is a blueprint for creating objects.
An instance is an individual object created from that class.
1
2
train1 = Train("15:45")
train2 = Train("16:00")
Both objects belong to the same Train class, but they contain different data.
1
2
3
4
5
print(train1.scheduled)
# 15:45
print(train2.scheduled)
# 16:00
Each instance maintains its own scheduled departure time.
This distinction is important when deciding which type of method to use.
2. Instance Methods
Instance methods are the most common type of method in Python.
They receive the instance itself as their first argument, conventionally named self.
1
2
3
4
5
6
class Train:
def __init__(self, scheduled):
self.scheduled = scheduled
def get_scheduled(self):
return self.scheduled
To call the method:
1
2
3
4
train = Train("15:45")
print(train.get_scheduled())
# 15:45
Python automatically passes the instance to the method.
In other words:
1
train.get_scheduled()
is equivalent to:
1
Train.get_scheduled(train)
When should we use instance methods?
Instance methods are appropriate when a method needs to:
- Access instance attributes
- Modify instance attributes
- Perform operations using an individual object’s state
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Train:
def __init__(self, scheduled):
self.scheduled = scheduled
def update_schedule(self, new_time):
self.scheduled = new_time
train = Train("15:45")
train.update_schedule("15:50")
print(train.scheduled)
# 15:50
The method modifies the state of a particular train instance.
3. Class Methods
Class methods operate on the class rather than a particular instance.
They are defined using the @classmethod decorator and receive the class itself as their first argument, conventionally named cls.
1
2
3
4
5
6
class Train:
operator = "South Western Railway"
@classmethod
def get_operator(cls):
return cls.operator
We can call this method without creating an instance:
1
2
print(Train.get_operator())
# South Western Railway
Unlike self, which refers to an individual object, cls refers to the class through which the method is called.
Class methods as alternative constructors
One common use of class methods is to provide alternative ways of creating objects.
1
2
3
4
5
6
7
8
9
10
11
class Train:
def __init__(self, scheduled, destination):
self.scheduled = scheduled
self.destination = destination
@classmethod
def from_dict(cls, data):
return cls(
scheduled=data["scheduled"],
destination=data["destination"]
)
Now we can create a Train instance directly from a dictionary:
1
2
3
4
5
6
7
8
9
data = {
"scheduled": "15:45",
"destination": "London Waterloo"
}
train = Train.from_dict(data)
print(train.destination)
# London Waterloo
Instead of manually extracting values every time an object is created, we can encapsulate that logic within a class method.
This pattern is particularly useful when working with API responses, configuration files, or external data sources.
4. Static Methods
Static methods are defined using the @staticmethod decorator.
Unlike instance methods and class methods, static methods do not automatically receive self or cls.
They behave similarly to regular functions but are associated with a class.
1
2
3
4
5
class Train:
@staticmethod
def calculate_delay(scheduled, estimated):
return estimated - scheduled
We can call the method directly through the class:
1
2
3
4
delay = Train.calculate_delay(45, 52)
print(delay)
# 7
This simplified example uses minute values within the same hour.
The calculation does not depend on any instance or class attributes. It only requires the arguments provided by the caller.
Therefore, neither self nor cls is necessary.
Static methods can also be called through an instance, although calling them through the class often makes their purpose clearer.
5. What Does @staticmethod Actually Do?
Consider the following implementation without the decorator:
1
2
3
4
class Train:
def calculate_delay(scheduled, estimated):
return estimated - scheduled
Calling the function directly through the class works:
1
2
Train.calculate_delay(45, 52)
# 7
However, calling it through an instance causes a problem:
1
2
3
train = Train()
train.calculate_delay(45, 52)
Python automatically passes the instance as the first argument.
As a result, the method receives three arguments instead of the expected two, raising a TypeError.
By adding @staticmethod:
1
2
3
4
5
class Train:
@staticmethod
def calculate_delay(scheduled, estimated):
return estimated - scheduled
Python no longer automatically passes the instance as the first argument.
Both calls now work:
1
2
3
4
Train.calculate_delay(45, 52)
train = Train()
train.calculate_delay(45, 52)
The decorator changes how the function is bound when accessed through a class or an instance.
6. Comparing the Three Types of Methods
| Feature | Instance Method | Class Method | Static Method |
|---|---|---|---|
| Decorator | None | @classmethod | @staticmethod |
| Automatically passed argument | self | cls | None |
Access to instance state through self | Yes | No | No |
Access to class state through cls | No | Yes | No |
| Callable without creating an instance | Requires an explicit instance | Yes | Yes |
| Typical purpose | Object-specific behaviour | Class-level behaviour | Independent utility operations |
The main difference is not simply whether a method can be called without creating an object.
It is whether the method requires access to instance state, class state, or neither.
Static methods can still access class attributes explicitly or receive objects as arguments. They simply do not receive an instance or class automatically.
7. Combining All Three Methods
The following example demonstrates all three method types within a single class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Train:
operator = "South Western Railway"
def __init__(self, scheduled, estimated):
self.scheduled = scheduled
self.estimated = estimated
# Instance method
def get_delay(self):
return self.calculate_delay(
self.scheduled,
self.estimated
)
# Class method
@classmethod
def get_operator(cls):
return cls.operator
# Static method
@staticmethod
def calculate_delay(scheduled, estimated):
return estimated - scheduled
Usage:
1
2
3
4
5
6
7
8
9
10
train = Train(45, 52)
print(train.get_delay())
# 7
print(Train.get_operator())
# South Western Railway
print(Train.calculate_delay(45, 52))
# 7
Each method has a distinct responsibility:
get_delay()uses data belonging to a particular train instance.get_operator()accesses a class-level attribute.calculate_delay()performs an independent calculation.
This separation makes the responsibilities of each method more explicit.
8. Static Methods in My RailOps AI Agent
In my RailOps AI Agent project, I use separate utility functions to calculate train delays and determine train statuses.
These functions are currently organised in a separate Python module called train_utils.py.
One possible alternative design would be to organise related functions inside a utility class using static methods.
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from datetime import datetime
class TrainUtils:
@staticmethod
def calculate_delay(scheduled, estimated):
scheduled_time = datetime.strptime(
scheduled, "%H:%M"
)
estimated_time = datetime.strptime(
estimated, "%H:%M"
)
difference = estimated_time - scheduled_time
return difference.total_seconds() / 60
Usage:
1
2
3
4
5
6
7
delay = TrainUtils.calculate_delay(
"15:45",
"15:52"
)
print(delay)
# 7.0
This calculation is independent of any particular object.
We do not need to create a TrainUtils instance because the calculation only depends on its input arguments.
This example assumes that both times refer to the same day. A production railway application would also need to handle midnight crossings, cancellations, missing values, and non-numeric estimated departure times.
9. Static Methods vs. Regular Functions
An important question is whether we actually need a class for independent utility functions.
Instead of:
1
2
3
4
5
class TrainUtils:
@staticmethod
def calculate_delay(scheduled, estimated):
return estimated - scheduled
We could simply write:
1
2
def calculate_delay(scheduled, estimated):
return estimated - scheduled
Both implementations can produce the same result.
The difference is primarily how the code is organised.
Static methods are useful when a function has a meaningful relationship with a particular class.
Regular module-level functions are often more appropriate when the functionality is independent and does not require object-oriented design.
For my current RailOps project, keeping utility functions in a separate train_utils.py module is also a perfectly valid approach.
There is no need to introduce a class simply to use @staticmethod.
Good software design is about choosing the simplest structure that meets the application’s requirements.
10. How to Choose the Right Method
When defining a new method, I can ask myself three questions:
Does the method need access to a particular object’s attributes?
Use an instance method with self.
Does the method need access to the class itself, or does it create new instances through an alternative constructor?
Use a class method with @classmethod.
Does the method perform an independent operation that logically belongs to the class?
Consider a static method with @staticmethod.
If the operation has no meaningful relationship with a class, a regular Python function may be the better option.
11. Key Takeaways
- Instance methods receive
selfand operate on individual objects. - Class methods receive
clsand operate on the class itself. - Static methods receive neither argument automatically.
- Static methods are useful for independent operations associated with a class.
- Class methods are commonly used to implement alternative constructors.
- Regular functions remain a valid alternative to static methods.
Understanding these three types of methods is not just about learning Python syntax. It is also about understanding object-oriented design and separating responsibilities within a software application.
As I continue developing AI applications, understanding these fundamental software engineering concepts will help me build cleaner, more maintainable, and more reliable systems.
Part of my learning journey in Python, software engineering, and Applied AI development.