python-类: 静态方法(staticmethod)、类方法(classmethod)和实例方法
前言
python类中方法有三种:静态方法(staticmethod)、类方法(classmethod)、实列方法。
本文主要介绍下静态方法(staticmethod)和类方法(classmethod)。
使用(fake)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class TestFuc( object ): def instance_fuc( self , x): print ( 'instance_fuc(%s,%s)' % ( self , x)) @classmethod def class_fuc( cls ,x): print ( 'class_fuc(%s,%s)' % ( cls ,x)) @staticmethod def static_fuc(x): print ( 'static_fuc(%s)' % x) test_fuc = TestFuc() # 实例方法 test_fuc.instance_fuc( 1 ) # 类方法 test_fuc.class_fuc( 1 ) TestFuc.class_fuc( 1 ) # 静态方法 test_fuc.static_fuc( 1 ) TestFuc.static_fuc( 1 ) |
应用
脱离了实际的应用场景,谈使用就是是耍流氓。上文介绍的"使用"仅仅展示如何定义(进入)和伪使用,真正的场景不会这样用的。
静态方法(staticmethod)和类方法(classmethod)并不常用。我喜欢在stackoverflow:What is the advantage of using static methods in Python?的一句话:"So they aren't useful for day-to-day methods"。尽管如此,我们依然要学习,并熟悉使用(原因:语言特性的完整、特殊场景的使用)。
目前,我看到网上介绍比较多应用用它们作为构造函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # staticmethod实现 class Date: def __init__( self ,year,month,day): self .year = year self .month = month self .day = day @staticmethod def now(): #用Date.now()的形式去产生实例,该实例用的是当前时间 t = time.localtime() #获取结构化的时间格式 return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建实例并且返回 @staticmethod def tomorrow(): #用Date.tomorrow()的形式去产生实例,该实例用的是明天的时间 t = time.localtime(time.time() + 86400 ) return Date(t.tm_year,t.tm_mon,t.tm_mday) a = Date( '1987' , 11 , 27 ) #自己定义时间 b = Date.now() #采用当前时间 c = Date.tomorrow() #采用明天的时间 print (a.year,a.month,a.day) print (b.year,b.month,b.day) print (c.year,c.month,c.day) |
继承类中的区别
- 子类的实例继承了父类的static_method静态方法,调用该方法,还是调用的父类的方法和类属性。
- 子类的实例继承了父类的class_method类方法,调用该方法,调用的是子类的方法和子类的类属性。
class Foo(object): X = 1 Y = 2 @staticmethod def averag(*mixes): return sum(mixes) / 1 @staticmethod def static_method(): return Foo.averag(Foo.X, Foo.Y) @classmethod def class_method(cls): return cls.averag(cls.X, cls.Y) class Son(Foo): X = 3 Y = 5 @staticmethod def averag(*mixes): return sum(mixes) / 2 p = Son() print(p.static_method()) print(p.class_method())
开源永流传
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)