ZetCode

Python staticmethod 函数

上次修改时间:2025 年 4 月 11 日

本综合指南探讨 Python 的 staticmethod 函数,该函数在类中创建静态方法。我们将介绍静态方法的定义、用法模式以及实际用例。

基本定义

staticmethod 是一个内置函数,用于将方法转换为静态方法。 静态方法不接收隐式的第一个参数。

主要特点:它们属于类而不是实例,无法访问或修改类/实例状态,并且使用类名调用。 它们充当与类相关的实用函数。

基本 staticmethod 用法

以下是在 Python 类中创建和使用静态方法的最简单方法。 此示例显示了装饰器语法和直接函数调用。

basic_static.py
class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b

# Call through class
print(MathUtils.add(5, 3))  # 8

# Call through instance (works but not recommended)
utils = MathUtils()
print(utils.add(10, 2))     # 12

这展示了一个执行加法的基本静态方法。 @staticmethod 装饰器表明此方法不需要 selfcls

虽然可以通过实例调用静态方法,但通过类调用它们更清晰,因为它们不依赖于实例状态。

类中的实用函数

静态方法通常用于逻辑上属于类但不需访问实例或类数据的实用函数。

date_utils.py
class DateUtils:
    @staticmethod
    def is_leap_year(year):
        if year % 4 != 0:
            return False
        elif year % 100 != 0:
            return True
        else:
            return year % 400 == 0

print(DateUtils.is_leap_year(2020))  # True
print(DateUtils.is_leap_year(2021))  # False

is_leap_year 方法是静态方法的一个好例子,因为它执行与日期相关的计算,但不需要实例数据。

这使该函数在 DateUtils 类命名空间中保持组织性,同时保持独立于任何特定的 DateUtils 实例。

替代构造函数

静态方法可以用作类的替代构造函数,提供创建实例的不同方式。

alternative_constructor.py
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    @staticmethod
    def from_tuple(coords):
        return Point(coords[0], coords[1])
    
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

# Regular constructor
p1 = Point(3, 4)
print(p1)  # Point(3, 4)

# Alternative constructor
p2 = Point.from_tuple((5, 6))
print(p2)  # Point(5, 6)

from_tuple 静态方法提供了一种创建 Point 对象的替代方法。 这是 Python 中的一种常见模式(参见 datetime)。

此类方法通常以 "from_" 开头命名,以表明它们是从不同输入格式构造对象的工厂方法。

与 Classmethod 比较

此示例演示了 staticmethodclassmethod 之间的区别,显示了何时使用每种方法。

static_vs_class.py
class Pizza:
    def __init__(self, ingredients):
        self.ingredients = ingredients
    
    @classmethod
    def margherita(cls):
        return cls(["mozzarella", "tomatoes"])
    
    @staticmethod
    def calculate_area(radius):
        return 3.14 * radius ** 2

# Classmethod usage - knows about the class
p1 = Pizza.margherita()
print(p1.ingredients)  # ['mozzarella', 'tomatoes']

# Staticmethod usage - no class knowledge
area = Pizza.calculate_area(12)
print(area)  # 452.16

margherita 类方法需要了解该类才能创建新实例,而 calculate_area 纯粹是一个数学函数。

当您需要访问该类时,请使用 classmethod,当该方法只是一个实用函数时,请使用 staticmethod

性能注意事项

静态方法可以通过避免常规实例方法的绑定开销来提供轻微的性能优势。

performance.py
import timeit

class Test:
    def instance_method(self):
        pass
    
    @staticmethod
    def static_method():
        pass

t = Test()

print("Instance method:", timeit.timeit(t.instance_method))
print("Static method:", timeit.timeit(t.static_method))

此基准测试表明,静态方法比实例方法略快,因为它们跳过了实例绑定步骤。 但是,差异通常可以忽略不计。

性能优势不应该是使用静态方法的主要原因 - 它们在逻辑组织和独立于实例状态方面更有优势。

最佳实践

资料来源

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 我从 2007 年开始撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程