Python 简明教程

Python - Static Methods

What is Python Static Method?

在 Python 中, static method 是一种无需调用任何实例的方法。它与类方法非常相似,但不同之处在于静态方法没有 − self 对象的引用或对类 − cls 的引用的强制参数。

静态方法用于访问给定类中的静态字段。因为它们与类绑定,而不是与实例绑定,所以它们不能修改类的状态。

How to Create Static Method in Python?

有两种方法可以创建 Python 静态方法 −

  1. Using staticmethod() Function

  2. Using @staticmethod Decorator

Using staticmethod() Function

Python 的名为 staticmethod() 的标准库函数用于创建静态方法。它接受一个方法作为参数,并将其转换成一个静态方法。

Syntax

staticmethod(method)

Example

在下方的 Employee 类中,showcount() 方法转换成一个静态方法。现在可以通过其对象或类本身的引用来调用这个静态方法。

class Employee:
   empCount = 0
   def __init__(self, name, age):
      self.__name = name
      self.__age = age
      Employee.empCount += 1

   # creating staticmethod
   def showcount():
      print (Employee.empCount)
      return
   counter = staticmethod(showcount)

e1 = Employee("Bhavana", 24)
e2 = Employee("Rajesh", 26)
e3 = Employee("John", 27)

e1.counter()
Employee.counter()

执行以上代码将打印以下结果 −

3
3

Using @staticmethod Decorator

创建静态方法的第二种方法是使用 Python @staticmethod 装饰器。当我们对一个方法使用这个装饰器时,它向解释器指示指定方法是静态的。

Syntax

@staticmethod
def method_name():
   # your code

Example

以下示例中,我们使用 @staticmethod 装饰器创建一个静态方法。

class Student:
   stdCount = 0
   def __init__(self, name, age):
      self.__name = name
      self.__age = age
      Student.stdCount += 1

   # creating staticmethod
   @staticmethod
   def showcount():
      print (Student.stdCount)

e1 = Student("Bhavana", 24)
e2 = Student("Rajesh", 26)
e3 = Student("John", 27)

print("Number of Students:")
Student.showcount()

运行以上代码将打印以下结果 −

Number of Students:
3

Advantages of Static Method

使用静态方法有许多优势,包括 -

  1. 由于静态方法无法访问类属性,因此可以将其用作实用函数来执行经常重复的任务。

  2. 我们可以使用类名调用此方法。因此,它消除了对实例的依赖性。

  3. 静态方法始终是可预测的,因为无论类状态如何,其行为保持不变。

  4. 我们可以将方法声明为静态方法以防止重写。