Instance, class and static methods

In Python, there are three main types of methods that can be defined within a class: instance methods, class methods, and static methods. Here’s an overview of each type:

  1. Instance methods: Instance methods are the most common type of method in Python classes. They are defined with the self parameter as the first parameter, which refers to the instance of the class that the method is being called on. Instance methods can access and modify instance variables of the object. They are called on the object and can be used to perform specific operations on the data stored in the object.
  2. Class methods: Class methods are defined with the @classmethod decorator and take the class as the first parameter instead of the instance. They can be used to modify class-level variables or perform operations that are not specific to a particular instance. Class methods are often used for creating alternate constructors, where you can create objects using different parameters than the default constructor.
  3. Static methods: Static methods are defined with the @staticmethod decorator and do not take any special first parameter. They can be called on either the class or the instance and do not modify the class or instance state. They are typically used for utility functions that are related to the class but do not depend on the state of the object or the class.

Code Example

In this example, MyClass defines three different types of methods:

  • An instance method (instance_method) which takes self as its first parameter and can access instance variables of the object it is called on.
  • A class method (class_method) which takes cls as its first parameter and can access class variables of the class it is called on.
  • A static method (static_method) which does not take any special first parameter and can be called on the class or an instance of the class, but cannot access any instance or class variables.
class MyClass:
    class_var = "class variable"

    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

    def instance_method(self):
        print("Instance method called")
        print(f"arg1: {self.arg1}, arg2: {self.arg2}")

    def class_method(cls):
        print("Class method called")
        print(f"class_var: {cls.class_var}")

    def static_method():
        print("Static method called")

# Create an instance of MyClass
obj = MyClass("foo", "bar")

# Call the instance method

# Call the class method

# Call the static method
Instance method called
arg1: foo, arg2: bar
Class method called
class_var: class variable
Static method called

This demonstrates how different types of methods can be defined in a class and called on instances or the class itself.