Instance method, Class method, and Static method in Python Class

This article is going to talk about the difference between instance method, class method, and static method in Python class.

Instance Method

Instance method is the most used method in python class. The instance method can be accessed by each instance. Each instance has its own instance variables. So, instance methods are used to access and modify instance variables.

Instance Method must have self argument as the first argument of the instance method. self just a name, it can be a different name. self refers to the instance.

class Employee:
# constructor
def __init__(self, ID=None, name=None, department=None):
self.ID = ID
self.name = name
self.department = department
# instance method
# a,b,c,d is instance variables
def demo(self, a, b, c=4, d=None):
print(a)
print(b)
print(c)
print(d)

Class Method

Class method works with class variables and access by class name. It also can access by instance, but we would like to access it by class name. All the class instances share the class variables and class method. So, class methods are used to access and modify class variables.

Class method must have @classmethod before the class method. And class method must have cls as the first argument. cls just a name, it can be a different name, cls refers to the class.

class Employee:
# class variable
# Access/Update by all instances
team = "IT"
# class method
@classmethod
def getTeamName(cls):
return cls.team
Steve = Employee()
# use class method
print(Steve.getTeamName())
# Prefer to use this way to use class method
print(Employee.getTeamName())

Static Method

Static method is not related to class variables or instance variables. It contains some fixed information and can not be modified.

Static method must have @staticmethod before the static method. And static method don’t have to use self or cls as first argument. It doesn’t have any mandatory argument.

class Employee:
# static method
# static method don't need to use self/cls
@staticmethod
def sMethod():
print("I am a static method")
# use static method
Steve.sMethod()
# Prefer to use this way to use static method
Employee.sMethod()