Python Converting a Normal Method onto a Static One

A static method is a method that does not depend on an instance or a class. You can define a static method by using @staticmethod decorator before the method definition. For example:

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

result = A.add(12, 12) # call static method by class name
print(result)

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. For example:

class A:
    count = 0 # class variable
 

    @classmethod
    def increment(cls): # class method
        cls.count += 1 # access class variable

    @staticmethod
    def add(a, b):
# static method
        return a + b # no access to class variable

A.increment()
# call class method by class name
print(A.count)
# 1

result = A.add(12, 12)
# call static method by class name
print(result)
# 24

A Static Method is a type of method in python classes that is bound to a particular state of the class. They can not access or update the state of the class. You can convert a normal method or instance method to a static method with the help of staticmethod(function)

class ABC:
    def abc(num1,num2):
        print(num1+numn2)

# changing torture_students into static method

ABC.abc = staticmethod(ABC.abc)

ABC.abc(4,5) # 9

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions