@classmethod:装饰器。顾名思义,对原物件进行外部修饰,不做内里的改变。
classmethod是用来指定一个类的方法为类方法,即顶着@classmethod所定义的函数,其所传递参数可为一个类,而非仅限于一般格式的诸如int、boolean等类型的参数。
使用方法如下:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
实例说明:
class Data_test(object):
def __init__(self,year=0,month=0,day=0):
self.day=day
self.month=month
self.year=year
def out_date(self):
print "year:"
print self.year
print "month:"
print self.month
print "day:"
print self.day
t = Data_test(2016,8,1)
t.out_date()
输出:
year:
2016
month:
8
day:
1
如果用户输入的是"2016-8-1" 这样的字符格式,那么就需要调用Date_test 类前做一下处理:
string_date='2016-8-1'
year,month,day=map(int,string_date.split('-'))
s=Data_test(year,month,day)
先把“2016-8-1”分解成 year,month,day 三个变量,然后转成int,再调用Date_test(year,month,day)函数。 也很符合期望。
能否把这个字符串处理的函数放到 Date_test 类当中呢?此时可使用装饰器@classmethod
class Data_test_1(object):
def __init__(self,year=0,month=0,day=0):
self.day=day
self.month=month
self.year=year
@classmethod
# 新添函数get_date。get_date函数的第一个参数是cls,表示调用当前类Data_test_1
def get_date(cls, data_as_string):
year, month, day = map(int, data_as_string.split('-'))
newDate = cls(year, month, day) # 返回的newDate是一个初始化后的类对象
return newDate
def out_date(self):
print "year:"
print self.year
print "month:"
print self.month
print "day:"
print self.day
调用:
r = Data_test_1.get_date("2016-8-1") # 先调用装饰器修饰的类函数,再走__init__
r.out_date()
输出:
year:
2016
month:
8
day:
1
这样子等于先调用装饰器@classmethod修饰的get_date()对字符串进行处理,然后才使用Data_test的构造函数初始化。
这样的好处就是以后重构类的时候不必要修改构造函数(即如果重构类,想要传参格式从(2006,01, 08)改成"2016-01-08",一般思路是修改类的__init__,但会同时影响本类中其他函数所需形参的参数格式。)只需要额外添加你要处理的函数(本例中添加了get_date())然后使用装饰符 @classmethod 就可以了。