Check out my article on medium.
Python is an object-oriented programming language, and one of its main features is that it allows defining class-level methods that can operate on the class itself, rather than an instance of the class. These methods are known as “static methods” and “class methods”. While both static methods and class methods can be called on the class rather than on an instance, they are different in the way they are declared, and how they are passed arguments. In this article, we will take a deep dive into static methods and class methods in Python, exploring what they are, how they are similar, and how they are different, along with Python code examples for better understanding.
Static methods are methods that are defined within a class, but are not tied to an instance of the class. They don’t need access to the class or its instances, and thus, don’t receive the instance as an argument (self) when they are called. A static method can be called either on the class itself, or on an instance of the class. In both cases, the result will be the same, as static methods don’t access the instance’s properties or methods.
To define a static method in Python, we use the “@staticmethod” decorator before the method definition. The syntax for defining a static method is as follows:
class MyClass: @staticmethod def my_static_method(arg1, arg2, ...): # implementation
Static methods are often used to define utility functions that don’t need access to the class or its instances. For example, consider a simple utility function that calculates the area of a circle, given its radius:
class Circle: @staticmethod def area(radius): return 3.14 * radius ** 2
In this example, the static method area doesn’t need access to the class or its instances, and thus, doesn’t receive the instance as an argument. It can be called on the class itself:
>>> Circle.area(5) 78.5
Or on an instance of the class:
>>> c = Circle() >>> c.area(5) 78.5
Here are some real world examples:
NumPy’s numpy.poly1d class uses a static method roots to calculate the roots of a polynomial.
import numpy as np p = np.poly1d([1, -3, 2, 1]) print(p.roots) Output: [ 1. 1.73205081 1. ]
NumPy’s numpy.linalg module uses a static method det to calculate the determinant of a matrix.
import numpy as np a = np.array([[1, 2], [3, 4]]) det = np.linalg.det(a) print(det) Output: -2.0
Class methods are methods that are defined within a class and are bound to the class itself, not to an instance of the class. They receive the class as the first argument when they are called, instead of the instance (self). This means that class methods can access and modify class-level properties, and can be used to implement class-level operations.
To define a class method in Python, we use the “@classmethod” decorator before the method definition. The syntax for defining a class method is as follows:
class MyClass: @classmethod def my_class_method(cls, arg1, arg2, ...): # implementation
In the above example, the cls argument refers to the class itself, and can be used to access and modify class-level properties.
Class methods are often used to implement class-level operations, such as creating new instances from class-level data. For example, consider a class that represents a point in 2D space:
class Point: def __init__(self, x, y): self.x = x self.y = y @staticmethod def distance_from_origin(x, y): return (x**2 + y**2)**0.5 @classmethod def from_tuple(cls, coords): return cls(*coords) p1 = Point(3, 4) print(Point.distance_from_origin(p1.x, p1.y)) p2 = Point.from_tuple((5, 12)) print(p2.x, p2.y) Output: 5.0 5 12
In this example, the distance_from_origin static method calculates the distance of the point from the origin, without requiring an instance of the class. The from_tuple class method creates a new instance of the Point class from a tuple of coordinates, making it easier to create new instances from existing data structures.
Here are some real world examples:
NumPy’s numpy.ndarray class uses a class method asarray to convert an object to an array.
import numpy as np list1 = [1, 2, 3] array = np.ndarray.asarray(list1) print(array) Output: [1 2 3]
NumPy’s numpy.matrix class uses a class method diag to create a diagonal matrix from a given array.
import numpy as np a = np.array([1, 2, 3]) b = np.matrix.diag(a) print(b) Output: [[1 0 0] [0 2 0] [0 0 3]]
In conclusion, static methods and class methods are an important aspect of object-oriented programming in Python. They allow for cleaner and more organized code by separating utility functions and class-level operations from instance-level operations. Both static methods and class methods have their specific use cases and provide different benefits, making them a valuable tool for writing well-structured code. As demonstrated by examples from popular open-source projects such as Django, NumPy, Pygame, and Requests, static methods and class methods are widely used in real-world applications and play a crucial role in writing clean and efficient code. Understanding and using static methods and class methods effectively can greatly improve the quality and readability of your code.