python类中方法有三种:静态方法(staticmethod)、类方法(classmethod)、实列方法。
本文主要介绍下静态方法(staticmethod)和类方法(classmethod)。
脱离了实际的应用场景,谈使用就是是耍流氓。上文介绍的"使用"仅仅展示如何定义(进入)和伪使用,真正的场景不会这样用的。
静态方法(staticmethod)和类方法(classmethod)并不常用。我喜欢在stackoverflow:What is the advantage of using static methods in Python?的一句话:"So they aren't useful for day-to-day methods"。尽管如此,我们依然要学习,并熟悉使用(原因:语言特性的完整、特殊场景的使用)。
目前,我看到网上介绍比较多应用用它们作为构造函数。
# 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)
转载于:https://www.cnblogs.com/flypig258/p/11428500.html