The Wayback Machine - https://web.archive.org/web/20240828001306/https://www.geeksforgeeks.org/class-method-vs-static-method-vs-instance-method-in-python/
Open In App

Class Method vs Static Method vs Instance Method in Python

Last Updated : 12 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help of examples in Python.

Class Method in Python

Class methods are associated with the class rather than instances. They are defined using the @classmethod decorator and take the class itself as the first parameter, usually named cls. Class methods are useful for tasks that involve the class rather than the instance, such as creating class-specific behaviors or modifying class-level attributes.

Syntax Python Class Method

class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
....
fun: function that needs to be converted into a class method
returns: a class method for function.

In this example, the MyClass defines a class variable class_variable, and the class_method is a class method that increments this variable. When calling the method with different values, it updates and returns the modified class variable. Instances obj1 and obj2 have their own instance_variable.

Python3
class MyClass:
    class_variable = 0

    def __init__(self, value):
        self.instance_variable = value

    @classmethod
    def class_method(cls, x):
        cls.class_variable += x
        return cls.class_variable

# Creating instances of the class
obj1 = MyClass(5)
obj2 = MyClass(10)

# Calling the class method
print(MyClass.class_method(3))  # Output: 3
print(MyClass.class_method(7))  # Output: 10

Output
3
10

Static Method in Python

Static methods, as the name suggests, are not bound to either the class or its instances. They are defined using the @staticmethod decorator and do not take a reference to the instance or the class as their first parameter. Static methods are essentially regular functions within the class namespace and are useful for tasks that do not depend on instance-specific or class-specific data.

Syntax Python Static Method

class C(object):
@staticmethod
def fun(arg1, arg2, ...):
...
returns: a static method for function fun.

In this example, the MathOperations class features static methods add and subtract for performing basic arithmetic operations. These methods can be directly invoked on the class without creating an instance, providing a convenient and state-independent way to perform mathematical operations.

Python3
class MathOperations:
    @staticmethod
    def add(x, y):
        return x + y

    @staticmethod
    def subtract(x, y):
        return x - y

# Using static methods without creating an instance
print(MathOperations.add(5, 3))        # Output: 8
print(MathOperations.subtract(10, 4))  # Output: 6

Output
8
6

Instance Method in Python

Instance methods are the most common type of methods in Python classes. They are associated with instances of a class and operate on the instance’s data. When defining an instance method, the method’s first parameter is typically named self, which refers to the instance calling the method. This allows the method to access and manipulate the instance’s attributes.

Syntax Instance Method

class MyClass:
def instance_method(self, arg1, arg2, ...):
# Instance method logic here
pass

In this example, the Person class defines an instance method introduce which returns a formatted introduction based on the instance’s name and age attributes. The instance person1 is created with the name “Kishan” and age 20, and invoking the introduce method prints a personalized introduction for that instance. Note that there’s a small typo in the comment mentioning the age; it should be 20 instead of 30.

Python3
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        return f"Hi, I'm {self.name} and I'm {self.age} years old."


# Creating an instance of the class
person1 = Person("Kishan", 20)

# Calling the instance method
print(person1.introduce())  # Output: Hi, I'm Kishan and I'm 30 years old.

Output
Hi, I'm Kishan and I'm 20 years old.

Python Class Method Vs. Static Method Vs. Instance Method

Aspect

Class Method

Static Method

Instance Method

Definition

A method bound to the class itself, defined with “@classmethod”

A method that does not receive an implicit first argument (‘self’ or ‘cls’), defined with “@staticmethod”

A method defined within a class, taking `self` as the first parameter, representing the instance.

Access

Can access class attributes and modify them.

Cannot access or modify class or instance attributes.

Can access and modify instance attributes.

First Argument

Receives ‘cls’ as the first argument representing the class.

No implicit first argument is passed to the method.

Receives `self` as the first argument representing the instance.

Usage

Often used for operations that modify or interact with class-level data.

Typically used for utility functions that don’t depend on instance or class state.

Commonly used for operations specific to individual instances.

Inheritance

Can be overridden in subclasses, with ‘cls’ referring to the subclass.

Can be called directly via the class or subclass, but not overridden.

Can be overridden in subclasses, with ‘self’ referring to the subclass instance.

Access Modifier

Typically used when the method needs access to class-level data.

Suitable when the method doesn’t rely on instance or class attributes.

Preferred when the method operates on instance-specific attributes.

Example Use

Calculating statistics across all instances of a class.

Formatting dates, performing mathematical operations.

Returning information specific to an instance, like its attributes.

Usefulness

Useful when dealing with class-level functionality and shared attributes.

Handy for standalone functions related to the class but not dependent on its state.

Essential for modifying and accessing instance attributes and behaviors.

Conclusion

In conclusion, we learn about the three commonly used methods in python, which are class method, static method and instance method. we also looked at how each of them work and how they are different from one another by looking at examples of programs with their code as well as outputs and a difference table that tells the difference between these 3 methods. you can also find some articles which are related to the methods in python programming below.



Similar Reads

Python VLC Instance - Creating MediaListPlayer Instance
In this article we will see how we can create a MediaListPlayer instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we
2 min read
Python VLC Instance - Creating MediaList Instance
In this article we will see how we can create a MediaList Instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can c
2 min read
Python VLC Instance - Creating new Media Instance
In this article we will see how we can create a Media instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can creat
2 min read
Python VLC Instance - Creating MediaPlayer Instance
In this article we will see how we can create a MediaPlayer instance from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can
2 min read
Class and Instance Attributes in Python
Class attributes Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. # Write Python code here class sampleclass: count = 0 # class attribute def increase(self): sampleclass.count += 1 # Calling increase() on an object s1 = sampl
2 min read
Python Attributes: Class Vs. Instance Explained
In Python, attributes are properties associated with objects. They can be variables or methods that are defined within a class or an instance of a class. Understanding the difference between class and instance attributes is fundamental in object-oriented programming. Here's an explanation: Python Attributes: Class Vs. Instance ExplainedBelow, is th
4 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
5 min read
Instance method in Python
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can
2 min read
Class or Static Variables in Python
All objects share class or static variables. An instance or non-static variables are different for different objects (every object has a copy). For example, let a Computer Science Student be represented by a class CSStudent. The class may have a static variable whose value is "cse" for all objects. And class may also have non-static members like na
7 min read
Launching AWS EC2 Instance using Python
In this article, we will learn how python can be used for creating and managing Amazon Web Services (AWS) such as Elastic Compute Cloud (EC2), Simple Storage Service (S3), Relational Database Service (RDS). For this purpose, we will use boto3 library of python, Boto is a Python package that provides interfaces to Amazon Web Services (AWS). Prerequi
4 min read
Python VLC MediaPlayer - Getting Instance of it
In this article we will see how we can get the instance of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. MediaPlayer cla
2 min read
Python VLC Instance – Deleting Single Media
In this article we will see how we can delete the single media from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can creat
2 min read
Python VLC Instance - Enumerate the defined audio output devices
In this article we will see how we can get the enumerate audio output devices from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance obje
3 min read
Python VLC Instance – Enabling Media/Broadcast
In this article we will see how we can enable or disable the single media from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object w
2 min read
Python VLC Instance – Setting Loop on the media
In this article we will see how we can set loop on the single media from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can
2 min read
Python VLC Instance – Play the specific Media/Broadcast
In this article we will see how we can play specific media from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create me
2 min read
Python VLC Instance – Stop the specific Broadcast
In this article we will see how we can specific media/broadcast from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can crea
2 min read
Python VLC Instance - Creating Media path
In this article we will see how we can create a media path from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create me
2 min read
Python VLC Instance - Setting Application Name
In this article we will see how we can set the application name from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can crea
2 min read
Python VLC Instance - Setting Meta Data of Application
In this article we will see how we can set the meta information of the application from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance
2 min read
Python VLC Instance - Unsetting Logging Callbacks
In this article we will see how we can unset the logging callbacks from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can c
2 min read
Python VLC - Instance
In this article we will see how we can create a Instance class instance in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create media player,
2 min read
Different ways to access Instance Variable in Python
Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute i.e. for every object, instance attribute is different. There are two ways to access the instance variable of class: Within the class by using self and object reference.Using getattr() method Example 1: Using Self and obj
2 min read
Creating Instance Objects in Python
In Python, an instance object is an instantiation of a class, and it is a unique occurrence of that class. Creating instance objects is a fundamental concept in object-oriented programming (OOP) and allows developers to work with and manipulate specific instances of a class. This article will explore the process of creating instance objects in Pyth
3 min read
How to create an instance of a Metaclass that run on both Python2 and Python3?
Metaclasses are classes that generate other classes. It is an efficient tool for class verification, to prevent sub class from inheriting certain class function, and dynamic generation of classes. Here we will discuss how to create an instance of a Metaclass that runs on both Python 2 and Python 3. Before delving into it, let's go through the code
3 min read
How to modify existing figure instance in Matplotlib?
In Python matplotlib.pyplot.figure() is used to modify existing Figure instance or make a new Figure instance. Generally, it is used to alter the basic properties of existing plots. It takes references to the concerned plots in case if it is used to alter the properties of the already formed plots. It returns the Figure instance and passes the same
4 min read
How to get value from SQLAlchemy instance by column name?
In this article, we will discuss how to get value from a table in SQL with the help of SQLAlchemy in Python. Database used: Installationpip install SQLAlchemy pymysql Note: pymysql is a dependency of sqlalchemy which users need to install so as to run our program. Get value by column name The given task can be performed by first creating an engine
2 min read
Create or Manage Heroku_postgres Database Instance
Heroku is a Platform-as-a-Service (PaaS) provider in the cloud that enables programmers to create, operate, and manage apps. In order to make it simpler for developers to deploy and manage their applications, Heroku offers a number of services and add-ons. Heroku Postgres, a managed SQL database service, is one example of such a service. We'll disc
4 min read
How to Clone and Save a Django Model Instance to the Database
In the realm of web development, Django stands out as a robust and versatile framework for building web applications swiftly and efficiently. One common requirement in Django projects is the ability to clone or duplicate existing model instances and save them to the database. This functionality is particularly useful when dealing with repetitive da
3 min read
Bound, unbound, and static methods in Python
Methods in Python are like functions except that it is attached to an object.The methods are called on objects and it possibly make changes to that object. These methods can be Bound, Unbound or Static method. The static methods are one of the types of Unbound method. These types are explained in detail below. Bound methods If a function is an attr
5 min read
Article Tags :
Practice Tags :