0
0
Pythonprogramming~5 mins

Difference between method types in Python

Choose your learning style9 modes available
Introduction

Methods are functions inside a class. Different types of methods help organize code and control how data is accessed or changed.

When you want a function that works with an object's data.
When you need a function related to the class but not to any one object.
When you want a function that can change or use class-level data.
Syntax
Python
class ClassName:
    def instance_method(self, args):
        # works with object data
        pass

    @classmethod
    def class_method(cls, args):
        # works with class data
        pass

    @staticmethod
    def static_method(args):
        # works without self or cls
        pass

instance_method always has self to access object data.

class_method uses cls to access class data and is marked with @classmethod.

Examples
Instance method: works with a specific dog object.
Python
class Dog:
    def bark(self):
        print('Woof!')
Class method: works with the class itself, not one dog.
Python
class Dog:
    species = 'Canine'

    @classmethod
    def get_species(cls):
        return cls.species
Static method: does not use object or class data.
Python
class Dog:
    @staticmethod
    def info():
        print('Dogs are friendly animals.')
Sample Program

This program shows three method types: instance method uses object data, class method uses class data, and static method works independently.

Python
class Car:
    wheels = 4  # class variable

    def __init__(self, color):
        self.color = color  # instance variable

    def show_color(self):
        print(f'This car is {self.color}.')  # instance method

    @classmethod
    def show_wheels(cls):
        print(f'A car has {cls.wheels} wheels.')  # class method

    @staticmethod
    def honk():
        print('Beep beep!')  # static method

my_car = Car('red')
my_car.show_color()
Car.show_wheels()
Car.honk()
OutputSuccess
Important Notes

Instance methods need an object to work.

Class methods can be called on the class or an object.

Static methods are like regular functions inside a class.

Summary

Instance methods use self to access object data.

Class methods use cls and @classmethod to access class data.

Static methods use @staticmethod and don't access object or class data.