Open In App

Class method vs Static method in Python

Last Updated : 30 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 evaluation shadows your function definition. A class method receives the class as an implicit first argument, just like an instance method receives the instance 

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.
  • A class method is a method that is bound to the class and not the object of the class.
  • They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
  • It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that will be applicable to all the instances.

What is the Static Method in Python?

A static method does not receive an implicit first argument. A static method is also a method that is bound to the class and not the object of the class. This method can’t access or modify the class state. It is present in a class because it makes sense for the method to be present in class.

Syntax Python Static Method: 

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

Class method vs Static Method

The difference between the Class method and the static method is:

  • A class method takes cls as the first parameter while a static method needs no specific parameters.
  • A class method can access or modify the class state while a static method can’t access or modify it.
  • In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
  • We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.

When to use the class or static method?

  • We generally use the class method to create factory methods. Factory methods return class objects ( similar to a constructor ) for different use cases.
  • We generally use static methods to create utility functions.

How to define a class method and a static method?

To define a class method in python, we use @classmethod decorator, and to define a static method we use @staticmethod decorator. 
Let us look at an example to understand the difference between both of them. Let us say we want to create a class Person. Now, python doesn’t support method overloading like C++ or Java so we use class methods to create factory methods. In the below example we use a class method to create a person object from birth year.

As explained above we use static methods to create utility functions. In the below example we use a static method to check if a person is an adult or not. 

One simple Example :

class method:

Python3




class MyClass:
    def __init__(self, value):
        self.value = value
 
    def get_value(self):
        return self.value
 
# Create an instance of MyClass
obj = MyClass(10)
 
# Call the get_value method on the instance
print(obj.get_value())  # Output: 10


Output

10

Static method:-

Python3




class MyClass:
    def __init__(self, value):
        self.value = value
 
    @staticmethod
    def get_max_value(x, y):
        return max(x, y)
 
# Create an instance of MyClass
obj = MyClass(10)
 
print(MyClass.get_max_value(20, 30)) 
 
print(obj.get_max_value(20, 30))


Output

30
30

Below is the complete Implementation 

Python3




# Python program to demonstrate
# use of class method and static method.
from datetime import date
 
 
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    # a class method to create a Person object by birth year.
    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)
 
    # a static method to check if a Person is adult or not.
    @staticmethod
    def isAdult(age):
        return age > 18
 
 
person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)
 
print(person1.age)
print(person2.age)
 
# print the result
print(Person.isAdult(22))


Output:

21
25
True

Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Class Method vs Static Method vs Instance Method in Python
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 o
5 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
5 min read
Python | Get a google map image of specified location using Google Static Maps API
Google Static Maps API lets embed a Google Maps image on the web page without requiring JavaScript or any dynamic page loading. The Google Static Maps API service creates the map based on URL parameters sent through a standard HTTP request and returns the map as an image one can display on the web page. To use this service, one must need an API key
2 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
Python Plotly - Exporting to Static Images
In this article, we will discuss how to export plotly graphs as static images using Python. To get the job done there are certain additional installations that need to be done. Apart from plotly, orca and psutil have to be installed. psutil (python system and process utilities) is a cross-platform Python package that retrieves information about run
2 min read
Convert Audio to Video using Static Images in Python
In this article, we are going to convert an audio file(mp3) to a video file(mp4) using the images provided by the user to be shown during the duration of the video using Python. To do this, we will first convert the images to a GIF file and then combining with the audio file to produce the final video file. Packages Required Mutagen: This Python pa
5 min read
Python Pyramid - Static Assets
A lightweight web framework in Python that converts small web apps to large web apps is called Pyramid. There are various circumstances when the user needs to add some images, HTML code, CSS code, etc. along with the Python code in the web app. These are called static assets and can be added using the Pyramid in Python. Python Pyramid - Static Asse
5 min read
wxPython - Create Static Box using Create() method
In this article we are going to learn about Static Box in wxPython. A static box is a rectangle drawn around other windows to denote a logical grouping of items. In this article we will create Static Box using two step creation, in order to do that we will use Create() method. Syntax: wx.StaticBox.Create(parent, id=ID_ANY, label="", pos=DefaultPosi
2 min read
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Article Tags :
Practice Tags :