Classmethod in Python
# Classmethod in Python
The classmethod() is an inbuilt function in Python, which returns a class method for a given function.
# fun: the function that needs to be convert into a class method
# return: a class method for function
@classmethod
def fun(cls, arg1, arg2, ...):
"""
cls: class
"""
1
2
3
4
5
6
7
2
3
4
5
6
7
# Class method vs. Static Method
- A class method takes
cls
as the first parameter while a static method needs no specific parameters. - A class method can access or modify the class state while a static method can’t access or modify it.
- In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
- We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.
Updated: 2021/09/15, 21:07:45