面试题:python 中 staticmethod 和 classmethod有什么区别
面试中经常会问到staticmethod 和 classmethod有什么区别?
首先看下官方的解释:
staticmethod:
class staticmethod
staticmethod(function) -> method
Convert a function to be a static method.
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C:
def f(arg1, arg2, ...): ...
f = staticmethod(f)
It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class.
Static methods in Python are similar to those found in Java or C++. For a more advanced concept,
它的一个作用就是将一个一个类的函数转为一个静态函数。静态函数的作用和java,c++的静态函数类似,作用一些全局变量等。
classmethod:
class classmethod
classmethod(function) -> method
Convert a function to be a class method.
A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
class C: def f(cls, arg1, arg2, ...): ... f = classmethod(f)
It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin.
classmethod 和 c++,java的类方法不同。类方法的参数是一个类,实例方法的参数是一个实例。
PS:遇到问题没人解答?需要Python学习资料?可以加点击下方链接自行获取
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76
例如下面的程序:
class A:
@staticmethod
def a():
print "this is a"
@classmethod
def b(rty):
print(rty)
print "this is b"
testa = A()
testa.a()
testa.b()
# 输出为:
# this is a
# __main__.A
# this is b
其中的__main__.A 为类A的名字。
如果将@classmethod去掉,则输出的结果为:
class A:
@staticmethod
def a():
print "this is a"
# @classmethod
def b(rty):
print(rty)
print "this is b"
testa = A()
testa.a()
testa.b()
# 输出为:
# this is a
# <__main__.A instance at 0x1070f03f8>
# this is b
可以看到这个时候rty的内容为,类A实例的地址。它和c++的类方法不是一回事儿,c++,java的类方法必须通过实例来调用。
标签:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人