通过静态方法和类方法能够把相关的函数封装到一个类里面,有效的将代码组织起来, 提高代码的可维护性;
普通方法:
class Date(object):
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
##普通方法
def __echo__(self):
print """
Day:%.2d
Month:%.2d
Year:%.4d
"""%(self.day,self.month,self.year)
d=Date(2018,4,3)
d.__echo__()
类方法:
class Date(object):
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
##普通方法
def __echo__(self):
print """
Day:%.2d
Month:%.2d
Year:%.4d
"""%(self.day,self.month,self.year)
@classmethod
def str_date(cls,s):
year,month,day=map(int,s.split("-"))
d=cls(year,month,day)
return d
# d=Date(2018,4,3)
# d.__echo__()
d=Date.str_date("2018-4-3") ###类调用str_date方法
print d
d.__echo__()
---->>
<__main__.Date object at 0x7f7f8da69e50>
Day:03
Month:04
Year:2018
静态方法
class Date(object):
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
def __echo__(self):
print """
Day:%.2d
Month:%.2d
Year:%.4d
"""%(self.day,self.month,self.year)
@classmethod
def str_date(cls,s):
year,month,day=map(int,s.split("-"))
d=cls(year,month,day)
return d
@staticmethod
def is_legal(s):
year, month, day = map(int, s.split('-'))
if not 0 < month <= 12 and 0 < day <= 31:
print '%s不合法' % s
else:
print '%s合法' % s
d=Date.is_legal("2018-1-3")
---->>>
2018-1-3合法
小结
普通方法: 没有@classmethod装饰器; 默认第一个参数是self(<__main__.Date object>); 调用时, 对象调用普通方法;
类方法: 有@classmethod装饰器; 默认第一个参数是cls(\<__main__.Date’>); 调用时, 类调用类方法;
静态方法:有@staticmethod装饰器,默认参数为可变参数,调用时,类调用静态方法