3 minutes
Python Static Methods Explained
staticmethod
is a built-in decorator in Python
that is used to define a static method inside a class.
A static method is a method that is not bound
to the instance of the class.
It does not have access to the instance
or class attributes and cannot modify them.
Instance Methods
First, let’s take a look at instance methods in Python. Instance methods or normal methods operate on an a specific instance of the class. They have access to the instance and class attributes.
Here is an example of an instance method in Python:
class MyClass:
def instance_method(self):
print(f"Instance method({self=})")
my_class = MyClass()
my_class.instance_method()
So, when you call an instance method,
the instance (my_class
in this case) is passed
as the first argument (self
).
This allows the method to access that specific instance attributes,
read and modify them.
Static Methods
Sometimes, you may want to define a method in a class that does not have access to the instance or class attributes or you don’t really care about the instance or class attributes. You might even want to call the method without creating an instance of the class. This is where static methods come in.
Syntax
To define a static method in Python,
you use the staticmethod
decorator
and remove the instance reference (self
in this case)
from the method signature.
btw, you can use any name for the instance reference argument, but
self
is the convention in Python.
Here is an example of a static method in Python:
class MyClass:
@staticmethod
def my_static_method():
...
Although you can call a static method using an instance of the class, you can also call it without referring to an instance by using the class itself as follows:
MyClass.my_static_method()
Static Methods Under The Hood
When you define a static method in Python, it is created as a function object in the class namespace. However, it ignores the owner.
Here is how it actually implemented:
class StaticMethod:
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
return self.func
When you call a static method, it wraps some function.
Then, when you retrieve the method using an instance of the class
in order to call it, the __get__
method is called.
It returns the wrapped function object and ignores the instance
and the class that it was called from.
In Python3.10 and later, static methods are made callable so you can call them directly even outside the class as mentioned above.
This is how the new implementation looks like:
class StaticMethod:
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
return self.func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
In this implementation, the __call__
method is added
so that it just forwards arguments to the wrapped function.