2 weeks, 5 days

Class method vs Static method in Python




Class methods are methods that are called on the class itself, not on a specific object instance. Therefore, it belongs to a class level, and all class instances share a class method. A class method is bound to the class and not the object of the class. It can access only class variables. It can modify the class state by changing the value of a class variable that would apply across all the class objects.

You can also use @classmethod decorator for class method definition.

Syntax Python Class Method:                                                                                       

                @classmethod                                                                   

                def fun(cls, arg1, arg2, ...):                                                                 

Class methods can be called by both class and object. These methods can be called with a class or with an object. 

class Cat:
    def show(cls):
        print(f'Cat name: {cls.__name__}')
    @classmethod
    def show_info(cls):
        print(f'Cat info: {cls.__name__}')
    shw = classmethod(show)
    
    @classmethod
    def info(cls):
        print(f'Cat: {cls.__name__}')
Cat.shw()
Cat.show_info()
cat = Cat()
cat.info()
Cat().show_info()

class Car:
    brands = list()
    
    def __init__(self):
        Car.brands.append(self)
        
    @classmethod
    def count(cls):
        return len(Car.brands)
        
c1 = Car()
c2 = Car()
c3 = Car()
print(Car.count())
class Employee:
    emp = []
    def __init__(self, name, department):
        self.name = name
        self.department = department
        Employee.emp.append(self)
    @classmethod
    def count(cls):
        return len(Employee.emp)
p1 = Employee("Emp1","P")
p2 = Employee("Emp2","M")
print(Employee.count())    


class Time:
    
    def __init__(self, day, month, year):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        date = cls(day, month, year)
        return date
    def __str__(self):
        return f"{self.day}-{self.month}-{self.year}"
        
date = Time.from_string('14-09-2022')    
print(date)

 

@classmethod the function is also callable without instantiating the class, but its definition follows Subclass, not Parent class, via inheritance, can be overridden by a subclass. That’s because the first argument for @classmethod the function must always be cls (class).

Factory methods are used to create an instance for a class using for example some sort of pre-processing.
We can dynamically delete the class methods from the class. In Python, there are two ways to do it:

By using the del operator                                                     
By using delattr() method                                                        

The del operator removes the instance method added by class. Use the del class_name.class_method syntax to delete the class method.

 

Static methods in Python are extremely similar to python class-level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class. staticmethod does not use the state of the object, or even the structure of the class itself. It could be a function external to a class. It is only put inside the class for grouping functions with similar functionality.

Syntax Python Static Method:                                              

                         class C(object):                                  

                             @staticmethod                         

                             def show(arg1, arg2, ...):                   
 

import time 

class Time:
    def get_current_time():
        return time.strftime('%H:%M:%S', time.localtime())
    current_time = staticmethod(get_current_time)
    
    @staticmethod
    def get_time():
        return time.strftime('%H:%M:%S', time.localtime())
print(Time.current_time())
print(Time.get_time())


import uuid

class Book:
    def __init__(self,book_name):
        self.id = self.get_id()
        self.book_name = book_name
    @staticmethod
    def get_id():
        return str(uuid.uuid4().fields[-1])
        
    def __str__(self):
        return f"Book(title='{self.book_name}', id='{self.id}')"
book = Book("Python")
print(book.__dict__.values())
book1 = Book("Algorithms")
print(book1)


We generally use the class method to create factory methods. Factory methods return class objects for different use cases. We generally use static methods to create utility functions.
 


Responses(0)