ZhangZhihui's Blog  

Sometimes we have to write methods that are related to the class but do not need any access to instance or class data for performing their work. These methods could be some helper or utility methods that are used inside the class but they can perform their task independently. There is no need to define these methods as instance methods or class methods as they do not need access to the instance object or the class object. We can define these methods as static methods by preceding them with the @staticmethod decorator. Unlike instance methods and class methods, static methods do not have any special first parameter. They can have regular parameters, but the first parameter has no special significance. So, when a static method is called, Python does not send the class object or the instance object as the first argument. This is why these methods cannot access or modify the instance state or the class state.

In the BankAccount class we saw earlier, we can add a static method named about that can be used to display general information about the class.

class BankAccount:
    ……………………
    ……………………
    
    @staticmethod
    def about():
        print('Information about BankAccount class ……')
        print('…………')
        print('…………')

BankAccount.about()

A static method can be invoked using either the class name or an instance name.

In the following Date class, you can write a static method is_leap that can be used as helper method in other methods of the class.

class Date:
    def __init__(self, d, m, y):
        self.d = d
        self.m = m
        self.y = y

     def method1(self, year):
        ………
        if Date.isleap(year):
            ………
            ………

     def method2(self, days):
        ………
        if Date.isleap(self.y):
            ………
            ………

    @staticmethod
    def is_leap(year):
         if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
              return True
         else:
              return False

So, when you have to create a helper or utility method, that contains some logic related to the class, turn it into a static method. For example, if you are creating a Fraction class, you can create a static method for finding hcf of two numbers. This method can be used to reduce the fraction to lowest terms.

 

posted on 2024-07-30 18:29  ZhangZhihuiAAA  阅读(5)  评论(0编辑  收藏  举报