关于Python3类方法、静态方法新解-创新互联
如下所示:

class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
# 实例方法
def tomorrow(self):
self.day +=1
def __str__(self):
return '{}/{}/{}'.format(self.year,self.month,self.day)
# 静态方法
@staticmethod
def format_date_str(date_str):
year, month, day = tuple(date_str.split('-'))
return Date(int(year),int(month),int(day))
# 类方法
# 这里的 cls 实际就是类本身,它将自己本身返回,不需要我们写返回的类名,更好一些
@classmethod
def format_str(cls, date_str):
year, month, day = tuple(date_str.split('-'))
return cls(int(year),int(month),int(day))
if __name__ == "__main__":
new = Date(2018,12,12)
print(new)
new.tomorrow()
print(new)
# 现在我们想输入一个日期字符串需要怎么做呢?
date_str = '2018-12-30'
year, month, day = tuple(date_str.split('-')) # 这里利用了tuple的拆包属性,将分开的列表分别赋给变量
new = Date(year,month,day)
print(new)
# 如果有静态方法,就会更加简单了
new = Date.format_date_str('2019-12-01')
print(new)
# 但是静态方法还要将类的名称返回,那有没有更好的方法呢
# 那就是类方法,类方法的原理就是 将输入的参数处理后 通过类方法返回一个实例对像,静态方法也是如此,但静态方法可以不返回实例 而返回其他的
new = Date.format_str('2019-9-01')
print(new)
# 那么问题来了?什么使用用静态方法,什么时候使用类方法呢?
# 原则上是:当需要返回实例时使用类方法,不需要返回实例对象时 直接使用静态方法就好了,
# 例如我们做验证日期字符串是否合法的时候没必要返回实例,那就使用 静态方法就可以了
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章标题:关于Python3类方法、静态方法新解-创新互联
浏览路径:http://www.jxjierui.cn/article/deoocs.html


咨询
建站咨询
