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

Class method vs Static method in Python

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

Python
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:-

Python
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)

Class method vs Static method in Python – FAQs

How to define a class method in Python?

A class method in Python is defined using the @classmethod decorator and takes cls as its first parameter, which refers to the class itself.

class MyClass:
    @classmethod
    def class_method(cls):
        print(f"Class method called from {cls.__name__}")

How to define a static method in Python?

A static method in Python is defined using the @staticmethod decorator and does not take any special first parameter (neither self nor cls).

class MyClass:
    @staticmethod
    def static_method():
        print("Static method called")

When should you use class methods over static methods in Python?

Class Methods: Use when you need to access or modify the class state or when the method needs to work with class variables or other class methods.

class MyClass:
    count = 0

    @classmethod
    def increment_count(cls):
        cls.count += 1

Static Methods: Use when the method does not access or modify class or instance state, and it performs a utility function that is related to the class but does not need access to class-specific data.

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

Can class methods and static methods be used interchangeably?

No, class methods and static methods are not interchangeable.

  • Class Methods: Can access and modify class state and are bound to the class, which makes them suitable for operations that involve the class itself.
  • Static Methods: Do not access or modify class or instance state and are used for utility functions that do not require access to the class or instance.

Using them interchangeably would be inappropriate as it would either give unnecessary access to the class state or lack access when needed.



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
9 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
Type Systems:Dynamic Typing, Static Typing & Duck Typing
Dynamic Typing: In Dynamic Typing, type checking is performed at runtime. For example, Python is a dynamically typed language. It means that the type of a variable is allowed to change over its lifetime. Other dynamically typed languages are -Perl, Ruby, PHP, Javascript etc. Let's take a Python code example to see if a variable can change type: ##
3 min read
wxPython - Remove static text on clicking button
In this article we are going to learn about how can we remove static text from the frame on clicking a button present in the same frame. We need to follow some steps: Step 1: Create a static text in frame. Step 1: Create a button in the same frame. Step 1: Assign event function for the button. Step 4: Destroy static text using Destroy() function. S
1 min read
wxPython Static Box
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. Note that while the previous versions required that windows appearing inside a static box be created as its siblings (i.e. use the same parent as the static box itself), since wxWidgets 2.
2 min read
wxPython - Get visual attributes of static box
In this article we are going to learn how can we get wx.VisualAttributes associated with Static Box. In order to do that we will use static GetClassDefaultAttributes() function. GetClassDefaultAttributes() function is used to return wx.VisualAttributes object for properties like background colour, foreground colour and font. Syntax: wx.StaticBox.Ge
1 min read
Django Static File
Static Files such as Images, CSS, or JS files are often loaded via a different app in production websites to avoid loading multiple stuff from the same server. This article revolves around, how you can set up the static app in Django and server Static Files from the same.Create and Activate the Virtual EnvironmentLet's understand how to add the Dja
3 min read
How to serve static files in Flask
Flask is a lightweight Web Server Gateway Interface or WSGI framework for web applications written in Python. It is designed to make web application development fast and easy and can scale to complex applications. This article describes and demonstrates how to serve various static files in Flask.  Serving Static Files in Flask Let's configure the v
5 min read
Why Django not Serve your Static Files in Debug False Mode
Django ships with a lightweight server called runserver that allows us to see live previews of our Django application. It promotes faster development, is great for development purposes, and is used during development not in production. DEBUG=True is a way to tell Django that we are currently in the development phase and the runserver can serve the
3 min read
Working with Static and Media Files in Django
Django's collectstatic management command is a powerful feature that helps manage static files by gathering them from various locations within a project and placing them into a single directory for deployment. This command is essential for preparing static files for production environments, ensuring that they are easily accessible and efficiently s
6 min read
Django Get the Static Files URL in View
In Django, static files such as CSS, JavaScript, and images are essential for building interactive and visually appealing web applications. While Django provides robust mechanisms to manage static files, we might need to access the URLs of these static files directly within our views, especially when we need to manipulate or dynamically generate co
3 min read
Call a Class Method From another Class in Python
In object-oriented programming, classes play a pivotal role in organizing and structuring code. Python, being an object-oriented language, allows the creation of classes and their methods to facilitate code modularity and reusability. One common scenario in programming is the need to call a method from one class within another class. In this articl
3 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Create Derived Class from Base Class Universally in Python
In object-oriented programming, the concept of inheritance allows us to create a new class, known as the derived class, based on an existing class, referred to as the base class. This facilitates code reusability and structuring. Python provides a versatile way to create derived classes from base classes universally, allowing for flexibility and sc
3 min read
Python: Call Parent class method
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. Example: # Python program to demonstrate # classes class cls: # Constructor def __init__(self, fname,
4 min read
Extend Class Method in Python
In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism. This is similar to overriding in Java and virtual methods
3 min read
Isoweekday() Method Of Datetime Class In Python
Isoweekday() is a method of the DateTime class that tells the day of the given date. It returns an integer that corresponds to a particular day. Syntax: datetime.isoweekday() Parameters: None Return Value: It returns an integer which corresponds to a day as per the table Integer ReturnedDay of the week1Monday2Tuesday3Wednesday4Thursday5Friday6Satur
3 min read
Isocalendar() Method Of Datetime Class In Python
The isocalendar() function is used to return a tuple of ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week.Therefore, ISO years always start with Monday.ISO year can start as yearly as 29th January or as late as 4th January of a Gregorian calendar.ISO years ca
2 min read
Isoformat() Method Of Datetime Class In Python
In this example, we will learn How to get date values in ISO 8601 format using Python. The Isoformat() function is used to return a string of date, time, and UTC offset to the corresponding time zone in ISO 8601 format. The standard ISO 8601 format is all about date formats for the Gregorian calendar. This format prescribes that a calendar date nee
4 min read
Violinplot in Python using axes class of Matplotlib
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. #Sample Code # Implementation of matplotlib functi
2 min read
Matplotlib.ticker.MultipleLocator Class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.ticker.MultipleLocator The matplotlib.ticker.MultipleLocator class is used for setting a tick for every integer multiple of a b
1 min read
fromisoformat() Function Of Datetime.date Class In Python
The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd. Syntax: @classmethod fromisoformat(date_string) Parameters: This function accepts a parameter which is illustrated below: date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date
2 min read
Matplotlib.gridspec.GridSpec Class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.gridspec.GridSpec The matplotlib.gridspec.GridSpec class is used to specify the geometry of the grid to place a subplot. For th
3 min read
Matplotlib.patches.CirclePolygon class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.patches.CirclePolygon The matplotlib.patches.CirclePolygon class is used for polygon-approximation of a circle patch. It is use
3 min read
Python Psycopg - Cursor class
The cursor class Enables Python scripts to use a database session to run PostgreSQL commands. The connection class is what creates cursors. cursor() method: They are permanently connected to the connection, and all instructions are run in the context of the database session covered by the connection. Cursors generated from the same connection aren'
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg