Try it here
Subscribe
Python OOPS : class and Static methods

Class method and Static method in Python

class_method_and_static_method_in_python

Class Method:

A class method is a method that is bound to a class rather than its object. It doesn't require creation of a class instance, much like staticmethod.

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

Example:

The class method can be created in two ways.

Using classmethod()

class Library:
    book_name = 'Python learning'
    def print_name(cls):
        print(f'The book name is {cls.book_name}')

Library.print_name = classmethod(Library.print_name)  # Now this method can be called as class method

Library.print_name()

classmethod() is considered un-Pythonic so in newer Python versions, you can use the @classmethod decorator for classmethod definition.

Using @classmethod

import datetime

class Library:
    def __init__(self, book_name, issue_date):
        self.book_name = book_name
        self.issue_date = issue_date

    @classmethod
    def issue_days(cls, book_name, issue_days):
        return cls(book_name, datetime.date.today() - datetime.timedelta(days=-issue_days))

    def display(self):
        print(f'The issue date of book {self.book_name} is : {self.issue_date}')

library = Library('Python',datetime.date(2020, 9 , 1))

library.display()

library1 = Library.issue_days('Python Learning', 20)
library1.display()

When to use class method?

1. Factory methods

Factory methods are those methods that return a class object (like constructor) for different use cases.

It is similar to function overloading in C++. Since, Python doesn't have anything as such, class methods and static methods are used.

2. Correct instance creation in inheritance

Whenever you derive a class from implementing a factory method as a class method, it ensures correct instance creation of the derived class.

You can create a static method for the above example but the object it creates, will always be hardcoded as Base class.

But, when you use a class method, it creates the correct instance of the derived class.

Static Method

A static method does not receive an implicit first argument.

Static methods, much like class methods, are methods that are bound to a class rather than its object.

They do not require a class instance creation. So, they are not dependent on the state of the object.

The static method can be created in two ways.

Using staticmethod()


class Calc:
    def add(a, b):
        return a + b
Calc.add = staticmethod(Calc.add) # Now this method can be called as Static method

print(f'The sum is : {Calc.add(6, 5)}')

Using staticmethod() is considered a un-Pythonic way of creating a static function. Hence, in newer versions of Python, you can use the @staticmethod decorator.

Using @staticmethod

class Calc:
    @staticmethod
    def add(a, b):
        return a + b

print(f'The sum is : {Calc.add(6, 5)}')

When to use static methods?

Static methods have a very clear use-case. When we need some functionality not w.r.t an Object but w.r.t the complete class, we make a method static. This is pretty much advantageous when we need to create Utility methods as they aren’t tied to an object lifecycle usually.

1- Grouping utility function to a class

Static methods have a limited use case because, like class methods or any other methods within a class, they cannot access the properties of the class itself.

However, when you need a utility function that doesn't access any properties of a class but makes sense that it belongs to the class, we use static functions.

2- Having a single implementation

Static methods are used when we don't want subclasses of a class change/override a specific implementation of a method.

The difference between a static method and a class method

Static method knows nothing about the class and just deals with the parameters.

Class method works with the class since its parameter is always the class itself.

Writer profile pic

Ganesh on Sep 13, 2020 at 02:09 am


This article is contributed by Ganesh. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

×

Forgot Password

Please enter your email address below and we will send you information to change your password.