staticmethod classmethod
类内的方法常见有三种 ,实例方法,类的静态方法,类方法,
staticmethod无法传入类本身,因此如果在类内需要访问类的任何方法或者属性,需要直接用类名来访问。好处是,这个是通过类访问的静态方法,类的静态方法,调用的时候需要用类名进行调用。这个有个坏处就是如果类名改变了,内部代码也要改。
classmethod,类方法,也是类访问,可以通过cls,或者self传入类,因此在类方法内访问类的属性或者方法时,直接通过cls或者self直接访问,这样就有个好处,如果类名发生改变,不需要改变内部的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | class Date: def __init__( self ,year,month,day): self .year = year self .month = month self .day = day def tomorrow( self ): self .day + = 1 @staticmethod def parse_from_string(date_str): year,month,day = tuple (date_str.split( '-' )) return Date( int (year), int (month), int (day)) @classmethod def from_string( cls ,date_str): year,month,day = tuple (date_str.split( '-' )) return cls ( int (year), int (month), int (day)) ''' @classmethod def from_string(self,date_str): year,month,day = tuple(date_str.split('-')) return self(int(year),int(month),int(day)) ''' @staticmethod def valid_str(date_str): year,month,day = tuple (date_str.split( '-' )) if int (year)> 0 and ( int (month)< 13 and int (month)> 0 ) and ( int (day)< = 31 and int (day)> 0 ): return True else : return False def __str__( self ): return '{year}{month}{day}' . format (year = self .year, month = self .month,day = self .day) if __name__ = = '__main__' : new_day = Date( 2018 , 12 , 20 ) new_day.tomorrow() print (new_day) date_str = '2018-12-20' # year,month,day = tuple(date_str.split('-')) # # print(year,month,day) # # new_day=Date(int(year),int(month),int(day)) # print(new_day) # #static method tmp_day = Date.parse_from_string(date_str) print (tmp_day) tmp_day = Date.from_string(date_str) print (tmp_day) print (Date.valid_str( '2018-06-12' )) |
Sophie的世界,转载请注明出处,谢谢。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人