当前位置: 首页 > news >正文

Python @staticmethod 装饰器与 staticmethod() 函数

Python @staticmethod 装饰器与 staticmethod{} 函数

  • 1. Python decorator (装饰器)
  • 2. `@staticmethod` decorator
  • 3. `staticmethod()` function
    • 3.1. Example 1
    • 3.2. Example 2
    • 3.3. Example 3
  • 4. `@staticmethod` decorator and `staticmethod()` function
  • References

Built-in Functions
https://docs.python.org/3/library/functions.html

The Python interpreter has a number of functions and types built into it that are always available.

1. Python decorator (装饰器)

Glossary - decorator
https://docs.python.org/3/glossary.html

A function returning another function, usually applied as a function transformation using the @wrapper syntax. Common examples for decorators are classmethod() and staticmethod().
返回另一个函数的函数,通常使用 @wrapper 语法形式来进行函数变换。 装饰器的常见例子包括 classmethod()staticmethod()

@classmethod - @staticmethod
https://docs.python.org/3/library/functions.html

The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent (装饰器语法只是一种语法糖,以下两个函数定义在语义上完全等价):

def f(arg):...
f = staticmethod(f)@staticmethod
def f(arg):...

The same concept exists for classes, but is less commonly used there.
同样的概念也适用于类,但通常较少这样使用。

See the documentation for function definitions and class definitions for more about decorators.

8. Compound statements - 8.7. Function definitions - 8.8. Class definitions
https://docs.python.org/3/reference/compound_stmts.html

2. @staticmethod decorator

Transform a method into a static method.
将 method 转换为 static method。

A static method does not receive an implicit first argument.
静态方法不会接收隐式的第一个参数。

To declare a static method, use this idiom:

class C:@staticmethoddef f(arg1, arg2, argN): ...

The @staticmethod form is a function decorator - see Function definitions for details.
@staticmethod 的形式称为函数的 decorator

8. Compound statements - 8.7. Function definitions
https://docs.python.org/3/reference/compound_stmts.html

A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()). Moreover, the static method descriptor is also callable, so it can be used in the class definition (such as f()).
静态方式既可以在类上调用 (such as C.f()),也可以在实例上调用 (such as C().f())。此外,静态方法 descriptor 也是可调用,因而它们可以在类定义中使用 (such as f())。

#!/usr/bin/env python
# coding=utf-8class C(object):@staticmethoddef fun():print(f"yongqiang");C.fun()  # 不实例化调用静态方法obj = C()
obj.fun()  # 实例化调用静态方法
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/yongqiang.py 
yongqiang
yongqiangProcess finished with exit code 0

Static methods in Python are similar to those found in Java or C++. Also, see classmethod() for a variant that is useful for creating alternate class constructors.

Built-in Functions - @classmethod
https://docs.python.org/3/library/functions.html

3. staticmethod() function

Like all decorators, it is also possible to call staticmethod as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method.
某些情况下需要从类主体引用函数并且你希望避免自动转换为实例方法。

For these cases, use this idiom:

def regular_function():...class C:method = staticmethod(regular_function)

For more information on static methods, see The standard type hierarchy.

3. Data model - 3.2. The standard type hierarchy
https://docs.python.org/3/reference/datamodel.html

Changed in version 3.10: Static methods now inherit the method attributes (__module__, __name__, __qualname__, __doc__ and __annotations__), have a new __wrapped__ attribute, and are now callable as regular functions.
静态方法现在继承了方法的属性 (__module__, __name__, __qualname__, __doc__ and __annotations__),并具有新的 __wrapped__ 属性,现在是属于与常规函数类似的可调用对象。

Python staticmethod() function is used to convert a function to a static function. Static methods are independent of class instances, meaning they can be called on the class itself without requiring an object of the class.

method = staticmethod(regular_function)

Parameters: A function that needs to be converted into a static method.
Returns: A static method version of the given function.

#!/usr/bin/env python
# coding=utf-8class Utility:def greet(name):return f"Hello, {name}!"greet = staticmethod(greet)  # Using staticmethod() function# Calling the static method
print(Utility.greet("yongqiang"))
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/yongqiang.py 
Hello, yongqiang!Process finished with exit code 0

Utility class has a static method greet() that doesn’t need an object to work. It simply takes a name and returns "Hello, {name}!". Since it’s a static method, we can call it directly using Utility.greet("yongqiang") without creating an instance of the class.

In object-oriented programming (OOP), a static method is a method that belongs to the class rather than an instance of the class.

Static methods are useful in situations where a function is logically related to a class but does not require access to instance-specific data.
当函数在逻辑上与类相关但不需要访问特定于实例的数据时,静态方法很有用。

Common use cases include:

  • Utility functions (e.g., mathematical operations, string formatting).
  • Operations that involve class-level data but do not need to modify it.
  • Methods that do not rely on instance variables and should be accessible without object creation.

Key characteristics of statics methods:

  • Do not require instantiation of the class.
  • Cannot modify the state of the class or instances.
  • Useful for utility functions related to a class but independent of instance data.

3.1. Example 1

MathUtils class has a static method add() that doesn’t need an object to work.

#!/usr/bin/env python
# coding=utf-8class MathUtils:def add(a, b):return a + badd = staticmethod(add)  # Using staticmethod() function# Calling the static method
res = MathUtils.add(9, 2)
print(f"res = {res}")
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/yongqiang.py 
res = 11Process finished with exit code 0

3.2. Example 2

If a method does not use any class properties, it should be made static. However, methods that access instance variables must be called via an instance.

#!/usr/bin/env python
# coding=utf-8class MathUtils:def __init__(self, a, b):self.a = aself.b = bdef add(m, n):return m + ndef diff(self):return self.a - self.b# Convert add() into a static method
MathUtils.add = staticmethod(MathUtils.add)# Calling the static method without creating an instance
print(MathUtils.add(1, 2))# Creating an instance to access instance-specific data
obj = MathUtils(5, 10)
print(obj.diff())

Static Method (add()): Since it’s static, we call it directly using DemoClass.add(1, 2), which prints 3.
Instance Method (diff()): It accesses instance-specific values (self.a and self.b) and returns their difference.

/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/yongqiang.py 
3
-5Process finished with exit code 0

3.3. Example 3

Static methods cannot access instance attributes but can access class-level variables.

#!/usr/bin/env python
# coding=utf-8class MathUtils:num = 40  # Class variabledef times():return MathUtils.num * 2times = staticmethod(times)  # Using staticmethod() function# Calling the static method
res = MathUtils.times()
print(f"res = {res}")

class-level variable num (40) is shared across instances. The static method times() directly accesses it. Since it’s static, we call it without creating an instance.

/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/yongqiang.py 
res = 80Process finished with exit code 0

4. @staticmethod decorator and staticmethod() function

  • The @staticmethod decorator is placed directly above the method, making it clear that it’s a static method.
  • Decorators are widely used in Python (@staticmethod, @classmethod, @property), so they align with common conventions.
  • Future modifications to the method are easier to manage without needing to manually reassign it with staticmethod().
#!/usr/bin/env python
# coding=utf-8class Utility:@staticmethoddef greet(name):return f"Hello, {name}!"# Calling the static method
print(f"res = {Utility.greet('yongqiang')}")
/home/yongqiang/miniconda3/bin/python /home/yongqiang/stable_diffusion_work/stable_diffusion_diffusers/yongqiang.py 
res = Hello, yongqiang!

References

[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/
[2] Python staticmethod() Function, https://www.geeksforgeeks.org/python/python-staticmethod-function/

http://www.lryc.cn/news/624097.html

相关文章:

  • Spring AI 集成阿里云百炼平台
  • C语言课程开发
  • C11期作业17(07.05)
  • Effective C++ 条款47: 使用traits classes表现类型信息
  • JVM常用工具:jstat、jmap、jstack
  • Transformer架构的数学本质:从注意力机制到大模型时代的技术内核
  • 因果语义知识图谱如何革新文本预处理
  • 机器学习案例——对好评和差评进行预测
  • Python开发环境
  • 说一下事件传播机制
  • Pandas数据结构详解Series与DataFrame
  • 【C#补全计划】多线程
  • 《解构WebSocket断网重连:指数退避算法的前端工业级实践指南》
  • 代码随想录刷题——字符串篇(五)
  • MySQL数据库初识
  • Linux 服务:iSCSI 存储服务配置全流程指南
  • 「数据获取」《中国文化文物与旅游统计年鉴》(1996-2024)(获取方式看绑定的资源)
  • ICCV 2025 | Reverse Convolution and Its Applications to Image Restoration
  • 一键管理 StarRocks:简化集群的启动、停止与状态查看
  • HTTP请求方法:GET与POST的深度解析
  • 【技术博客】480p 老番 → 8K 壁纸:APISR × SUPIR × CCSR「多重高清放大」完全指南
  • PCA 实现多向量压缩:首个主成分的深层意义
  • 平行双目视觉-动手学计算机视觉18
  • Go语言并发编程 ------ 锁机制详解
  • C++析构函数和线程退出1
  • C++继承(2)
  • Eclipse Tomcat Configuration
  • Docker-14.项目部署-DockerCompose
  • Docker入门:容器化技术的第一堂课
  • 飞算JavaAI赋能高吞吐服务器模拟:从0到百万级QPS的“流量洪峰”征服之旅