All you need to know about classmethod and staticmethod .What’s The Difference Between Static and Class Methods in Python?
Apart from instance methods — which are the most common class members in the context of object oriented programming — classes in Python can also have static and class methods. The language comes with two decorators, namely
@classmethod , that allow us to define such members in classes. It is important to understand these concepts as they will help you write object-oriented Python which is more clear and properly structured and will eventually make maintenance much easier.
In this article, we are going to explore what each of the two does, how to create them and also in which cases you should use one over the other.
Take a moment to go through the code below as this will be used as the example Python class that we are gonna use to explore a few concepts.
class Employee: NO_OF_EMPLOYEES = 0 def __init__(self, first_name, last_name, salary): self.first_name = first_name self.last_name = last_name self.salary = salary self.increment_employees() def give_raise(self, amount): self.salary += amount @classmethod def employee_from_full_name(cls, full_name, salary): split_name = full_name.split(' ') first_name = split_name last_name = split_name return cls(first_name, last_name, salary) @classmethod def increment_employees(cls): cls.NO_OF_EMPLOYEES += 1 @staticmethod def get_employee_legal_obligations_txt(): legal_obligations = """ 1\. An employee must complete 8 hours per working day 2\. ... """ return legal_obligations
🔵 Intellipaat Data Science with Python course: https://intellipaat.com/python-for-data-science-training/In this Data Science With Python Training video, you...
Enroll in our Data Science with Python training in Chennai. Best Data Science with Python Training courses in Chennai for 100% Job Placements Support.
🔥Intellipaat Python for Data Science Course: https://intellipaat.com/python-for-data-science-training/In this python for data science video you will learn e...
Master Applied Data Science with Python and get noticed by the top Hiring Companies with IgmGuru's Data Science with Python Certification Program. Enroll Now
Become a data analysis expert using the R programming language in this [data science](https://360digitmg.com/usa/data-science-using-python-and-r-programming-in-dallas "data science") certification training in Dallas, TX. You will master data...