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 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.
|
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.
|