Class Method vs Instance Method in Python

1. Introduction

In Python, methods defined within a class can be of two types: instance methods and class methods. An instance method is a method that operates on an instance of the class and has access to the instance's attributes. It takes the instance as its first argument (traditionally named self). A class method, on the other hand, works with the class itself and not with instances. It takes the class as its first argument (traditionally named cls) and can modify class state that applies across all instances.

2. Key Points

1. First Argument: Instance methods take the instance (self) as the first argument, class methods take the class (cls).

2. Decorator: Instance methods don't use a specific decorator, class methods use @classmethod.

3. Access to Data: Instance methods can access and modify instance data, class methods can access and modify class state.

4. Usage: Instance methods are used for regular functionality related to objects, class methods for factory methods, or actions that pertain to the class.

3. Differences

Aspect Instance Method Class Method
First Argument Instance (self) Class (cls)
Decorator None @classmethod
Access to Data Instance data Class state
Usage Regular object functionality Factory methods, class actions

4. Example

class MyClass:
    # Instance Method
    def instance_method(self):
        return 'instance method called', self

    # Class Method
    @classmethod
    def class_method(cls):
        return 'class method called', cls

# Create instance of MyClass
my_instance = MyClass()

# Call instance method
instance_method_output = my_instance.instance_method()

# Call class method
class_method_output = MyClass.class_method()

Output:

Instance Method Output:
('instance method called', <MyClass instance>)
Class Method Output:
('class method called', <class 'MyClass'>)

Explanation:

1. The instance_method output shows it was called on an instance, as indicated by self.

2. The class_method output reflects that it was called on the class, as indicated by cls.

5. When to use?

- Use instance methods when you need to perform an operation that uses data specific to an object.

- Use class methods when the operation pertains to the class as a whole, such as creating factory methods or modifying class-wide data.

Comments