说明
《Python 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
在 Python 中,静态方法(static method)是类的一种方法,它不依赖于类的实例或类本身。静态方法使用 @staticmethod 装饰器来定义,不需要额外的 self 或 cls 参数。静态方法通常用于一些逻辑上属于类的方法,但在实现上不需要访问类的实例属性或类属性。
定义方法如下:
class MyClass:
    @staticmethod
    def static_method():
        print("This is a static method.")
静态方法可以通过类本身或类的实例来调用:
# 通过类调用静态方法
MyClass.static_method()  # 输出: This is a static method.
# 通过实例调用静态方法
obj = MyClass()
obj.static_method()      # 输出: This is a static method.
静态方法可以实现一些独立的工具函数,例如数学运算等:
class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b
    @staticmethod
    def subtract(a, b):
        return a - b
print(MathUtils.add(5, 3))       # 输出: 8
print(MathUtils.subtract(5, 3))  # 输出: 2
将一些相关的函数放在一个类中,使代码更加结构化:
class StringUtils:
    @staticmethod
    def is_palindrome(s):
        return s == s[::-1]
    @staticmethod
    def to_uppercase(s):
        return s.upper()
print(StringUtils.is_palindrome("radar"))  # 输出: True
print(StringUtils.to_uppercase("hello"))   # 输出: HELLO
虽然类方法更常用于工厂方法,但静态方法也可以实现类似的功能:
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    @staticmethod
    def create_child(name):
        return Person(name, 0)
child = Person.create_child("Alice")
print(child.name)  # 输出: Alice
print(child.age)   # 输出: 0
静态方法是 Python 中一种非常实用的工具,用于实现不依赖于类实例或类属性的方法。它们通过 @staticmethod 装饰器来定义,可以通过类本身或类的实例来调用。静态方法主要用于实现工具方法、逻辑分组和有时用于工厂方法。通过静态方法,可以将一些相关的函数组织在一起,使代码结构更加清晰和逻辑化。
关于 Python 内置装饰器,可以参考 @staticmethod 。
更新时间:2024-06-16 17:05:07 标签:python 静态方法