Today, we are going to learn what class method and static method are and the difference between them. We can define three types of methods (instance, class, and static) in a class. Most of you might be familiar with the instance method as it is a commonly used method. It takes an implicit parameter self, which points to the object instance that invoked the method. As the name suggests, it is bound to the object instance and thus can access the object state (properties and methods).
Let’s now see what class and static methods are.
Class Method
A class method is a method that has access to the class state. While the instance method takes a reference to its object instance as a parameter, the class method takes a pointer to its class as its parameter. By convention, we denote it by cls. The class method is bound to its class. To create it, use the @classmethod decorator.
@classmethod
def function1(cls, param1, param2, ...., paramN):
#function body
Static Method
The static method, on the other hand, does not take an object instance or a class, which means that it can’t access their states. It is also bound to its class. The @staticmethod decorator is used to create a static method.
@staticmethod
def function2(param1, param2, ...., paramN):
#function body
Examples and Usage
Let’s take a simple test example to get a clear idea.
class Sample:
num1 = 10
def __init__(self, num2):
self.num2 = num2
def testinstance(self, num3):
print("This is a regular method")
return self.num1 + self.num2 + num3
@classmethod
def testclass(cls, num3):
print("This is a class method")
return cls.num1 + num3
@staticmethod
def teststatic(num3):
print("This is a static method")
return num3
The above code has a Sample
class that has a class variable num1
and an object variable num2
. It also contains one method of each type. As you can see, the instance method has access to the class and object states. The Class method has access to the class state only, and the static method does not have access to either of them.
obj1 = Sample(20)
print(obj1.testinstance(30))
Output
60
To call an instance method, we need to instantiate an object. If you call it directly on the class, you will get a type error.
The class method and the static method, however, can be invoked using either the object instance or the class itself. However, it makes more sense to invoke the class method using the class name because it is completely related to the class.
obj1 = Sample(20)
print(obj1.testclass(30))
print(Sample.testclass(30))
print(obj1.teststatic(30))
print(Sample.teststatic(30))
Output
40
This is a class method
40
This is a static method
30
This is a static method 30
This example was to get the basic idea of these methods. Let’s now take a more practical example. Class methods are often used as alternative constructors or as factory methods, i.e., to create instances based on different use cases. Let’s say we have a class Student
having attributes name, grade, and date of admission. The constructor takes the admission date as a year, month, and day. Some users provide the information in this format, but others give the admission date in a string as “YYYY-MM-DD”. For the string form, we will use a class method as an alternative constructor, which will allow our users to input information in the way they want.
class Student:
def __init__(self, name, grade, year, month, day):
self.name = name;
self.grade = grade;
self.year = year;
self.month = month;
self.day = day;
@classmethod
def from_string(cls, name, grade, admission_date):
year, month, day = admission_date.split("-")
return cls(name, grade, year, month, day)
def displayInformation(self):
print(f"Name: {self.name}, Grade: {self.grade}")
print(f"Date of Admission: Year: {self.year}, Month: {self.month}, Day: {self.day}")
The from_string()
class method is used as the alternative constructor to split the string by “-“. The displayInformation()
method displays the information of the student. Let’s now go ahead and create student instances using the default and the alternative constructor.
student1 = Student("Ashton", 10, 2005, 7, 1)
student1.displayInformation()<br/>
Output
Date of Admission: Year: 2005, Month: 7, Day: 1
student1 = Student.from_string("Agar", 9, "2008-1-15")
student1.displayInformation()
Output
Date of Admission: Year: 2008, Month: 1, Day: 15
Cool, right?
Static methods are used to create helper or utility functions. These methods have a logical connection with the class but do not use class or object state. Let’s add a static method that takes the score of a student and outputs the remarks. This method has a logical connection with the Student class but does not use its properties or methods.
class Student:
def __init__(self, name, grade, year, month, day):
self.name = name;
self.grade = grade;
self.year = year;
self.month = month;
self.day = day;
@classmethod
def from_string(cls, name, grade, admission_date):
year, month, day = admission_date.split("-")
return cls(name, grade, year, month, day)
@staticmethod
def getRemarks(score):
if score >=90 and score <=100:
return "Excellent"
elif score >= 80 and score < 90:
return "Very Good"
elif score >= 70 and score < 80:
return "Good"
elif score >= 60 and score < 70:
return "Keep it up"
elif score >= 0 and score < 60:
return "Improve"
else:
return "Invalid Score"
def displayInformation(self):
print(f"Name: {self.name}, Grade: {self.grade}")
print(f"Date of Admission: Year: {self.year}, Month: {self.month}, Day: {self.day}")
student1 = Student("Ashton", 10, 2005, 7, 1)
print(student1.getRemarks(75))
Output