| by Arround The Web | No comments

Class Method vs Static Method in Python

Python, being an object-oriented programming language, offers developers various tools and concepts to handle different scenarios efficiently. Two of these concepts are class methods and static methods, which provide specific functionalities in Python classes.

This article aims to discuss the differences between class methods and static methods, their uses, and their significance in Python programming at an advanced level.

What are Decorators?

Class methods and static methods both use “decorators” to indicate their respective purposes. By decorating the methods, it becomes clearer to other developers and aids in understanding the intended functionality of a particular method. Decorators also enhance the readability and maintainability of the codebase.

What are Class Methods?

A method that is part of the class rather than an instance of the class is referred to as a class method in Python. It is denoted using the “@classmethod” decorator and takes the class itself as an implicit first parameter. When performing activities that call for access to class-level characteristics or methods, class methods are commonly used.

Class methods are primarily utilized for creating alternate constructors, accessing the class-specific attributes, or performing operations that don’t require the instance’s state.

Let’s take a look at the syntax of the class method:

class C(object):

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

fun: function which has to be transformed into a class method.

returns: a class method for function.

Below is given an example of a class method:

class Rect:

    area = 10
 
    @classmethod
    def get_area(cls):
        return cls.area
 
    @classmethod
    def set_area(cls, new_area):
        cls.area = new_area

print(Rect.get_area())

Rect.set_area(20)

print(Rect.get_area())

A class called “Rect” is defined in the above code. A class attribute “area” with an initial value of 10 is present in the class. Additionally, it has the “get_area” and “set_area” class methods. The “cls” parameter, which refers to the class itself, is what the “get_area” class method uses to access the current value of the area class property.

The “cls” parameter and an additional parameter named “new_area” are both passed to the “set_area” class method. It changes the area of all instances of the “Rect” class by setting the area class attribute to the value of “new_area”.

The code calls “Rect.get_area()”, which returns the area’s starting value, 10, which is 10. The area class attribute of “Rect” is then changed to 20 by calling “Rect.set_area(20)”. “Rect.get_area()” is then called one more, returning the revised value of the area, which is now 20.

Output

Alternative Constructors with Class Methods

Class methods are commonly employed to implement alternative constructors within a class. By using the class method decorator, developers can provide additional ways to instantiate objects based on specific parameters or logic, establishing a more flexible and intuitive coding experience.

What are Static Methods?

On the other hand, static methods are methods that are independent of either the class or the instance. The “@staticmethod” decorator is used to indicate them, and they don’t accept any implicit parameters. “Static methods” are employed when we need to perform operations that are not related to instance-specific data but are still meaningful within the class context.

The syntax of the static method is as follows:

class C(object):

    @staticmethod
    def fun(arg1, arg2, ...):
        ...

fun: function which has to be transformed into a static method.

returns: a static method for a fun function.

Below is given an example of a static method:

class add_num:

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

print(add_num.add(5, 5))

The code that is provided defines the Python class “add_num”, which has the static function “add()”. The “add()” method accepts two numbers as parameters, x and y. The + operator is used internally to accomplish the addition of these two numbers, and the result is returned.

The add function on the class “add_num” is then called directly by the code with inputs 5 and 5. The outcome of this operation, which is the addition of the two numbers (5 + 5), is printed to the console as the output of the “add” method, which is called.

Output

Utilizing Static Methods for Utility Functions

Static methods, on the other hand, serve as utility functions within the class context. They can perform operations that are relevant to the class but independent of its instances, making them reusable across various parts of the application. This enhances code modularity and promotes clean, concise programming practices.

When to Use These Methods?

Class methods are commonly employed when the functionality requires interaction with class variables, initialization, or instantiation procedures. Examples include factory methods, alternative constructors, and modifying class-level attributes. Alternatively, static methods suit scenarios where functionality needs to be encapsulated within the class but does not rely on any class-level data.

What are the Differences Between Class and Static Methods

Key differences between class and static methods are:

1: Method Invocation

The primary distinction between class methods and static methods lies in how they are invoked. Class methods are accessed using the class as a reference and are implicitly passed the class as an argument, while static methods can be invoked both using the class reference or the instance of the class.

2: Inheritance

Another aspect where class methods and static methods differ is their behavior in inheritance scenarios. When using class methods within an inheritance hierarchy, the class of the object calling the method is the one affected. Conversely, static methods preserve their behavior independent of the subclass they are invoked from.

3: Instance Methods

While instance methods are the primary means of working with object-oriented concepts in Python, class and static methods offer additional modularity and flexibility. While class and static methods can work independently of instances, simplifying some use cases, instance methods need to be generated before they can be invoked.

Conclusion

Class and static methods in Python cater to different requirements of code organization, functionality inheritance, and reusability. While class methods provide flexibility in object instantiation and class-specific operations, static methods excel in modularity and utility within the class context.

Share Button

Source: linuxhint.com

Leave a Reply