Instance, class and static methods

Methods within a class can be categorized into three main types:

  • instance methods,
  • class methods,
  • static methods

Each type serves a different purpose and is used differently within a class. Here is an overview of each:

Instance Methods

Instance methods are the most common type of method in a class. They operate on an instance of the class and can access and modify the attributes of the instance. These methods must include self as the first parameter, which is a reference to the instance of the class.

Example:

class MyClass:
    def __init__(self, value):
        self.value = value

    def instance_method(self):
        return f'This is an instance method. Value: {self.value}'

# Creating an instance
obj = MyClass(10)
print(obj.instance_method())  # Output: This is an instance method. Value: 10

Class Methods

Class methods are methods that operate on the class itself rather than on instances of the class. They cannot modify instance-specific data but can modify class-level data. These methods use cls as the first parameter, which is a reference to the class.

Class methods are defined using the @classmethod decorator.

Example:

class MyClass:
    class_variable = 'Class Variable'

    @classmethod
    def class_method(cls):
        return f'This is a class method. {cls.class_variable}'

# Calling a class method
print(MyClass.class_method())  # Output: This is a class method. Class Variable

Static Methods

Static methods are similar to class methods, but they do not operate on the class or its instances. They do not take self or cls as the first parameter and cannot modify class or instance state. Static methods are utility functions that belong to the class but do not require access to class-specific data.

Static methods are defined using the @staticmethod decorator.

Example:

class MyClass:
    @staticmethod
    def static_method(x, y):
        return f'This is a static method. Sum: {x + y}'

# Calling a static method
print(MyClass.static_method(5, 7))  # Output: This is a static method. Sum: 12

Summary

  • Instance Methods:
    Operate on instances of the class and can access and modify instance-specific data. They require self as the first parameter.
  • Class Methods:
    Operate on the class itself and can modify class-level data. They require cls as the first parameter and are marked with the @classmethod decorator.
  • Static Methods:
    Do not operate on the class or its instances and cannot modify class or instance state. They do not require self or cls and are marked with the @staticmethod decorator.