跳至主要內容

静态方法

刘春龙原创...小于 1 分钟Python教程文档

Python 中允许定义与“类对象”无关的方法,称为“静态方法”。

“静态方法”和在模块中定义普通函数没有区别,只不过“静态方法”放到了“类的名字空间里面”,即在你名下,与你无关,需要通过“类调用”。

静态方法通过装饰器@staticmethod来定义,格式如下:

@staticmethod
def 静态方法名([形参列表]) :
    方法体

要点如下:

  1. @staticmethod必须位于方法上面一行
  2. 调用静态方法格式:类名.静态方法名(参数列表)
  3. 静态方法中访问实例属性和实例方法会导致错误
class Student:
    count = 0  # 类属性
    company = "JIAMEI"  # 类属性

    def __init__(self, name):
        self.name = name  # 实例属性

    def say_score(self):  # 实例方法
        Student.count += 1

    @classmethod
    def printCompany(cls):  # 类方法
        print(cls.company)

    @staticmethod
    def add(a, b):  # 静态方法
        print(a + b)


s1 = Student("张三")
s1.say_score()
Student.printCompany()  # JIAMEI
Student.add(1, 2)  # 3
上次编辑于:
贡献者: 刘春龙
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.7