python中的静态方法和类方法
静态方法实际上就是普通函数,定义形式是在def行前加修饰符@staticmethod,只是由于某种原因需要定义在类里面。静态方法的参数可以根据需要定义,不需要特殊的self参数。可以通过类名或者值为实例对象的变量,已属性引用的方式调用静态方法
类方法定义形式是在def行前加修饰符@classmethod,这种方法必须有一个表示其调用类的参数,一般用cls作为参数名,还可以有任意多个其他参数。类方法也是类对象的属性,可以以属性访问的形式调用。在类方法执行时,调用它的类将自动约束到方法的cls参数,可以通过这个参数访问该类的其他属性。通常用类方法实现与本类的所有对象有关的操作。
1 ##coding:utf-8 2 class TestClassMethod(object): 3 4 METHOD = 'method hoho' 5 6 def __init__(self): 7 self.name = 'leon' 8 9 def test1(self): 10 print 'test1' 11 print self 12 13 @classmethod 14 def test2(cls): 15 print cls 16 print 'test2' 17 print TestClassMethod.METHOD 18 print '----------------' 19 20 @staticmethod 21 def test3(): 22 print TestClassMethod.METHOD 23 print 'test3' 24 25 26 a = TestClassMethod() 27 a.test1() 28 a.test2() 29 a.test3() 30 TestClassMethod.test3()
test1 <__main__.TestClassMethod object at 0x0000000003DDA5F8> <class '__main__.TestClassMethod'> test2 method hoho ---------------- method hoho test3 method hoho test3
实例方法隐含的参数为类实例,而类方法隐含的参数为类本身。
静态方法无隐含参数,主要为了类实例也可以直接调用静态方法。
所以逻辑上类方法应当只被类调用,实例方法实例调用,静态方法两者都能调用。
在贴一例,供参考:
1 class TestClassMethod(object): 2 3 METHOD = 'method hoho' 4 5 def __init__(self): 6 self.name = 'leon' 7 8 def test1(self): 9 print 'test1' 10 print self 11 12 @classmethod 13 def test2(cls): 14 print cls 15 print 'test2' 16 print TestClassMethod.METHOD 17 print '----------------' 18 19 @staticmethod 20 def test3(): 21 print TestClassMethod.METHOD 22 print 'test3' 23 24 25 a = TestClassMethod() 26 a.test1() 27 a.test2() 28 a.test3() 29 TestClassMethod.test3()
test1 <__main__.TestClassMethod object at 0x0000000003DDA5F8> <class '__main__.TestClassMethod'> test2 method hoho ---------------- method hoho test3 method hoho test3
一只混迹在规划圈的giser,喜欢数据分析和模型
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?