English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations sur les fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemple de la méthode staticmethod() en Python

Python built-in functions

staticmethod()内置函数为给定函数返回静态方法。

staticmethod()的语法为:

staticmethod(function)

使用staticmethod()被认为是创建静态函数的非Python标准方式。

因此,在较新版本的Python中,您可以使用@staticmethod装饰器。

@staticmethod的语法为:

@staticmethod
def func(args, ...)

staticmethod()参数

staticmethod()方法采用单个参数:

  • function -需要转换为静态方法的函数

staticmethod()返回值

staticmethod()对于作为参数传递的函数,返回静态方法。

什么是静态方法?

静态方法与类方法非常相似,是绑定到类而不是对象的方法。

它们不需要创建类实例。因此,它们不依赖于对象的状态。

静态方法和类方法之间的区别是:

  • 静态方法对类一无所知,只处理参数。

  • 类方法与类一起使用,因为其参数始终是类本身。

可以通过类及其对象来调用它们。

Class.staticmethodFunc()
或甚至
Class().staticmethodFunc()

Example1:使用staticmethod()创建一个静态方法

class Mathematics:
    def addNumbers(x, y):
        return x + y
# 创建addNumbers静态方法
Mathematics.addNumbers = staticmethod(Mathematics.addNumbers)
print('总数是:', Mathematics.addNumbers(5, 10))

Output result

总数是: 15

什么时候使用静态方法?

1.将实用程序功能分组到一个类

静态方法的使用受到限制,因为与类方法或类中的任何其他方法一样,静态方法无法访问类本身的属性。

但是,当您需要一个不访问类的任何属性但知道它属于该类的实用程序函数时,我们将使用静态函数。

Example2:将实用程序功能创建为静态方法

class Dates:
    def __init__(self, date):
        self.date = date
        
    def getDate(self):
        return self.date
    @staticmethod
    def toDashDate(date):
        return date.replace("/", "-)
date = Dates("15-12-2016)
dateFromDB = "15/12/2016"
dateWithDash = Dates.toDashDate(dateFromDB)
si(date.getDate() == dateWithDash):
    print("Equal")
else:
    print("Unequal")

Output result

Equal

Here, we have a Dates that is only suitable for dates with dashes (-) of the class. But in our previous database, all dates were represented by slashes.

To convert slash dates to dates with dashes (-) date, we created a utility function toDashDate in Dates.

This is a static method because it does not need to access any attributes of Dates itself, but only needs parameters.

We can also create it outside the toDashDate class, but since it is only applicable to dates, it is logical to keep it within the Dates class.

2.single implementation

When we do not want the subclass of the class to change/Static methods can be used when specific implementations of methods need to be overwritten.

Example3How to work with static methods together with inheritance?

class Dates:
    def __init__(self, date):
        self.date = date
        
    def getDate(self):
        return self.date
    @staticmethod
    def toDashDate(date):
        return date.replace("/", "-)
class DatesWithSlashes(Dates):
    def getDate(self):
        return Dates.toDashDate(self.date)
date = Dates("15-12-2016)
dateFromDB = DatesWithSlashes("15/12/2016)
if(date.getDate() == dateFromDB.getDate()):
    print("Equal")
else:
    print("Unequal")

Output result

Equal

Here, we do not want the DatesWithSlashes subclass to override the static utility method toDashDate, as it has only one use, that is, to change the date to dash-date.

By rewriting the method getDate() in the subclass, we can easily take advantage of static methods to exert our own advantages, thus making it work normally with the DatesWithSlashes class.

Python built-in functions