Python class & static method

In this post i will try to explain python’s class and static method and how to use them.

 prerequisites

In order to understand class and static method, specially class method, one should know the difference between class and instance variables.

    class AClass:
        a_class_variable = ''
    class AClass:
        def a_method(self):
            self.a_instance_variable = ''

You may have seen class and static method while reading or writing a class in python programming. Though they looks very similar but serves different purpose. And can be quite puzzling for beginners.

Syntax:

    class Salad:

        restaurant_name = 'XY-Z'

        def __init__(self, recipe):
            self.recipe = recipe

        @staticmethod
        def mix_ingredients(p, q):
            return p + q

        @classmethod
        def choose_restaurant(cls, restaurant_name):
            cls.restaurant_name = restaurant_name
            return cls

In the example above there are three methods in class Salad, __init__, mix_ingredients, choose_restaurant.

Class method __init__ is special method starting with double underscore called constructor method of the class it belongs to, python uses this method to create class’s object. Also notice that it takes self as its first argument. keyword self refer to a particular instance of the class. Thus it can also be called a instance method.

Class method mix_ingredients does not take self as first argument. Which means it has no need to depend on the state of the class’s instance. So it can be treated as static method by decorating it with @staticmethod decorator. These methods are same as any other python function defined outside the class.

Its always a good idea to identify static methods when writing classes in python and mark them static. So when python instantiating a class object it does not create a copy of these method. Which may affect the application overall performance because every new instance of the class occupies some space in memory when created.

Class method choose_restaurant takes cls as its first argument. Which refers to a class itself. Methods takes a class as their first argument are considered class method and has to be marked as such with @classmethod decorator.

    salad = Salad('Garden salad')
    print('Restaurant: {}'.format(salad.restaurant_name))
    print('Salad Recipe: {}'.format(salad.recipe))

Output:

    Restaurant: XY-Z
    Salad Recipe: Garden salad

In the above example we created a new salad with the default restaurant. But the help of class method we can create a new restaurant and then create a salad in that restaurant.

    salad_restaurant = Salad.choose_restaurant('PQ-R')
    salad = salad_restaurant('Vegetable salad')
    print('Restaurant: {}'.format(salad.restaurant_name))
    print('Salad Recipe: {}'.format(salad.recipe))

Output:

    Restaurant: PQ-R
    Salad Recipe: Vegetable salad

Above pattern is known as factory pattern. Without factory pattern we have to hard code the class name and making any class inheriting this class unable to use factory method for their purpose.

 Conclusion:

Class methods are mostly useful for creating factory methods - methods which instantiate objects in specific fashion.

In python class methods can be written as secondary constructor to change some of class’s default data. While maintaining the __init__ as default constructor.

Since static methods are just like any other function so it does not have to be in the class. However, if the behaviour of the function is not generic but rather more case specific it’s a good practice to write it within the class definition. This way they can be accessed directly using class instance without importing them explicitly.

 
0
Kudos
 
0
Kudos

Now read this

Multi-processing vs Multi-threading

In python, multiprocessing and multithreading are common terms when it comes to improve the application performance using concurrent and parallel programming. Let’s look at each term individually. Multithreading–ability to run code on... Continue →