Python class method vs static method
In this post, you will learn two method types of Python- class method and static method. The difference between these two methods can be confusing for beginners. That is the reason we composed this post for understanding the differences and when to utilize everyone. Before understanding the differences, it's essential to understand the decorator design pattern and how to define a method in Python.
Method in python
In Python, a function is a group of related statements that play out a particular task. Functions help break our program into small modular chunks. As our program develops bigger and bigger, functions make it more coordinated and manageable. The method is just a function object created by a def statement. It begins with the keyword def followed by the function name and parentheses ( ( ) ). The code block within every function starts with a colon (:) -
Syntax of defining a functiondef function_name(parameters):
"""docstring"""
statement(s)
Decorator Patterns
The decorator is a Python design pattern. The design patterns are used by the developers to represent the pattern in software or web applications. There are many design patterns available in Python to achieve different tasks. The Decorator pattern allows a user to dynamically add new functionality to an existing object without changing its structure. Decorators have to quickly go before a function or class presentation. They start with the @ sign. There is no need to put enclosures at the end except if you are passing in arguments.
@classmethod
The Class method knows about their class. It can access and modify the class state. The @classmethod decorator is used for defining classmethod. The @classmethod method has a mandatory first argument, that is the class itself (cls). This is generally used to create factory methods. A factory method can return a class object for different use cases.
Syntax of class methodclass class_name:
@classmethod
def function_name(cls, args):
# function body
return value
@staticmethod
For static methods, we need to specify @staticmethod decorator. This method does not know about class state and cannot access or modify the class state. This method does not take any specific parameter. This is generally used to create utility functions.
Syntax of static methodclass class_name:
@staticmethod
def function_name(args):
# function body
return value
Example of @classmethod and @staticmethod
from datetime import date as dt
class Student:
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 cal_stu_age(stu_class, name, year):
return stu_class(name, dt.today().year - year)
def __str__(self):
return 'Student Name: {} and Age: {}'.format(self.name, self.age)
s1 = Student('Priska', 12)
print(s1)
s2 = Student.cal_stu_age('Abhishek', 2011)
print(s2)
print(Student.isAdult(25))
print(Student.isAdult(16))
Output of the above code -
Student Name: Priska and Age: 12
Student Name: Abhishek and Age: 10
True
False
Related Articles
Python multiline string
glob in Python
Python heap implementation
zip function in Python
Remove last element from list Python
Check if list is empty Python
Remove element from list Python
Python split multiple delimiters
Python loop through list
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Remove character from string Python
Python compare two lists
Insert data in MySQL database from an HTML form using Django
Alphabet pattern programs in Python