类中用普通方法:
def get_date(string_date):
year,month,day=map(int,string_date.split("-"))
return year,month,day
class Date_test(object):
day=0
month=0
year=0
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=Date_test(2019,9,1)
t.out_date() # year :
# 2019
# month :
# 9
# day :
# 1
t1=Date_test("2019-9-2")
t1.out_date() # year :
# 2019-9-2
# month :
# 0
# day :
# 0
y,m,d=get_date("2019-9-3")
r=Date_test(y,m,d)
r.out_date() # year :
# 2019
# month :
# 9
# day :
# 3
使用 @classmethod后:
class Date_test(object):
day=0
month=0
year=0
def __init__(self,year=0,month=0,day=0):
self.day=day
self.month=month
self.year=year
@classmethod
def get_date(cls,string_date):
year,month,day=map(int,string_date.split("-"))
date=cls(year,month,day)
return date
def out_date(self):
print("year : ")
print(self.year)
print("month : ")
print(self.month)
print("day : ")
print(self.day)
t=Date_test(2019,9,1)
t.out_date() # year :
# 2019
# month :
# 9
# day :
# 1
t1=Date_test("2019-9-2")
t1.out_date() # year :
# 2019-9-2
# month :
# 0
# day :
# 0
r=Date_test.get_date("2019-9-3")
r.out_date() # year :
# 2019
# month :
# 9
# day :
# 3
可见,@classmethod主要用于构造函数,若不用这个字段,想要多种构造函数就很不方便,只能在new里面写一堆if isinstance,有classmethod之后就可以用classmethod来写不同的构造函数;另外可用来为一个类创建一些预处理的实例,节约内存
class Fuck:
sex = '每日' #这就是非绑定的属性
@staticmethod
def sta():
return Fuck.sex
@classmethod
def cla(cls):
return cls.sex #@classmethod里面必须要传入一个参数,这个参数代表就是当前的类
class Fuck_everybody(Fuck): #因为Fuck_everybody继承了父类Fuck,所以Fuck_everybody可以调用父类的sta()方法与cla()方法
pass
print(Fuck_everybody.sta()) # 每日
print(Fuck_everybody.cla()) # 每日
# 然后我突然不爽,把Fuck删掉了
del Fuck
#那么,你再试试
# print(Fuck_everybody.sta()) # 报错:NameError: name 'Fuck' is not defined
print(Fuck_everybody.cla()) # 每日
#虽然删掉,但是仍能执行
staticmethod主要用途是限定namespace,也就是说这个函数虽然是个普通的function,但是它只有这个class会用到,不适合作为module level的function,这时候就把它作为staticmethod;增加代码易读性;无需实例化,节约内存
区别:@staticmethod 会硬编码,就是说,方法中返回的类名必须与当前的 class 名称一致
@classmethod 是软编码,该方法传递的第一个参数使 cls ,cls 默认绑定了当前的类名