Class method vs static method in Python
We use @classmethod decorator to define a class method in python and @staticmethod decorator to define a static method.
When to use these methods?
- We use class method to make factory methods. Factory methods can return class object for different use cases.
- We use static methods to do utility functions.
Class Method
The @classmethod decorator, is a built-in functiondecorator which gets evaluated after your function is defined.
A class method takes the class as implicit first argument.
Syntax:
class C(object): @classmethod def fun(cls, arg1, arg2, ...): .... fun: function that needs to be converted into a class method returns: a class method for function.
Static Method
A static method does not take any implicit first argument.
Syntax:
class C(object): @staticmethod def fun(arg1, arg2, ...): ... returns: a static method for function fun.
What are the differences between Classmethod and StaticMehtod?
Class Method | Static Method |
The class method takes implicit cls (class) as first argument. | The static method does not take any argument. |
Class method can access the class state and modify the class state. | Static Method can’t access or modify the class state. |
The class method knows about the state of that class. | Static methods do not know about class state and are used to do some utility tasks by taking some parameters. |
@classmethod decorator is used to define a class method. | @staticmethod decorator is used to define a static method. |
Let us take at an example to understand the difference between both of them.
Example:
from datetime import date as dt class Person: def __init__(self, name, age): self.name = name self.age = age @staticmethod def isAdult(age): if age > 18: return True else: return False @classmethod def emp_from_year(emp_class, name, year): return emp_class(name, dt.today().year - year) def __str__(self): return 'Person Name: {} and Age: {}'.format(self.name, self.age) e1 = Person('mayank', 25) print(e1) e2 = Person.emp_from_year('David', 1985) print(e2) print(Person.isAdult(25)) print(Person.isAdult(16))
Output:
Share: