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 = name
self.department = department
# instance method
# a,b,c,d is instance variables
def demo(self, a, b, c=4, d=None):

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
def getTeamName(cls):
Steve = Employee()
# use class method
# Prefer to use this way to use class method

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
def sMethod():
print("I am a static method")
# use static method
# Prefer to use this way to use static method