Monday 13 May 2024

Static methods vs class methods in Python

 Background

In the last post, we saw how to work with classes in Python. We saw private methods, instance variables, class variables, etc. In this post, we are going to explore static and class methods in Python. If you are from a Java background you would use class methods or static methods interchangeably but that is not the case with Python. 



Class methods in Python

  • Class methods are your methods that are at class level (they belong to the class & not individual instances).
  • They will get the reference to the class as the implicit first argument (similar to how instance methods get a reference to self)
  • Class methods have access to class variables /state and can modify them
Consider the following  example:
class Employee:

    BASE_INCOME = 10000

    def __init__(self, name :str) -> None:
        self.name = name

    @classmethod
    def get_base_income_with_cls_method(cls) -> int:
        return cls.BASE_INCOME

    @classmethod
    def set_base_income_with_cls_method(cls, income: int) -> None:
        cls.BASE_INCOME = income


e = Employee("Aniket")
print(Employee.BASE_INCOME)
print(Employee.get_base_income_with_cls_method())
print(e.get_base_income_with_cls_method())
Employee.set_base_income_with_cls_method(100)
print(Employee.BASE_INCOME)
print(e.get_base_income_with_cls_method())
e.set_base_income_with_cls_method(10)
print(Employee.BASE_INCOME)
print(e.get_base_income_with_cls_method())


It prints:

10000
10000
10000
100
100
10
10

Notice

  • You declare a method as a class method using @classmethod decorator
  • The class method automatically gets an implicit argument cls which is a reference to the class.
  • BASE_INCOME is defined outside __init__ and hence is a class variable.
  • We have defined two class methods get_base_income_with_cls_method and set_base_income_with_cls_method which get and set that class variable (You actually do not need this and can do it directly with class reference E.g., Employee.BASE_INCOME=X etc. but have added to show how the class method has access to class variables via cls - 1st implicit argument).
  • Changes made to the state by class methods are reflected across all instances of the class.
This is what you would know as a static method in Java.

Now let's see what a static method in Python looks like:

Static methods in Python


  • A static method does not get an implicit first argument (as class methods did). 
  • Similar to class methods a static method is also bound to the class (and not the object of the class) however this method can’t access or modify the class state. 
  • It is simply present in a class because it makes sense for the method to be present in class (rather than at individual instance level, for eg., some utility methods).
  • You can create a static method using @staticmethod decorator.

Consider the following example:
class Employee:

    def __init__(self, name: str) -> None:
        self.name = name

    @staticmethod
    def is_same_name(name1: str, name2: str) -> bool:
        return name1 == name2


print(Employee.is_same_name("Aniket", "Abhijit"))
print(Employee.is_same_name("Aniket", "Aniket"))


It prints:

False
True

As you can see these can be used for simple utility methods.


When to use class methods and static methods?

  • Class methods are generally used to create factory methods. Factory methods return class objects depending on the usecase.
  • Static methods are generally used to create utility functions.




Related Links

No comments:

Post a Comment

t> UA-39527780-1 back to top