Python - 静态方法


静态方法没有强制参数,例如对对象的引用- self或对类的引用- cls。Python 的标准库 fimction staticmethod() 返回静态方法。

在下面的 Employee 类中,方法被转换为静态方法。现在可以通过其对象或类本身的引用来调用此静态方法。

class Employee: empCount = 0 def __init__(self, name, age): self.__name = name self.__age = age Employee.empCount += 1 #@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()

Python 还有 @staticmethod 装饰器,可以方便地返回静态方法。

@staticmethod def showcount(): print (Employee.empCount) e1.showcount() Employee.showcount()