Pyhton @staticmethod

@staticmethod是一个内置的修饰符,它在Python中定义类中的静态方法。静态方法不接收任何引用参数,无论它是由类的实例调用还是由类本身调用。

@staticmethod 特点

  • 声明一个静态方法
  • 不可以有 cls or self 参数.
  • 既不可以访问类的方法,又不可以访问实例的方法 .
  • 可以通过ClassName.MethodName() 或者 object.MethodName().调用
  • 不可以返回一个实例

定义一个静态方法

class Student:
    name = 'unknown' # class attribute
    
    def __init__(self):
        self.age = 20  # instance attribute

    @staticmethod
    def tostring():
        print('Student Class')

不可以访问类属性、实例属性

class Student:
    name = 'unknown' # class attribute
    
    def __init__(self):
        self.age = 20  # instance attribute

    @staticmethod
    def tostring():
        print('name=',name,'age=',self.age)

会报错

>>> Student.tostring()
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    Student.tostring()
  File "<pyshell#21>", line 7, in display
    print('name=',name,'age=',self.age)
NameError: name 'name' is not defined

与@classmethod 比价

  • 类方法将cls作为第一个参数,而静态方法不需要特定的参数。
  • 类方法可以访问或修改类状态,而静态方法不能访问或修改它。

使用场景

我们通常使用类方法来创建工厂方法。工厂方法为不同的用例返回类对象(类似于构造函数)。
我们通常使用静态方法来创建实用函数。

参考:https://www.tutorialsteacher.com/python/staticmethod-decorator

不要小瞧女程序员
原文地址:https://www.cnblogs.com/shix0909/p/15037667.html