@staticmethod和@classmethod都不需要进行实例化即可调用方法函数,都可以 类名.函数名()或类名().函数名() 方式进行调用
@staticmethod调用时可以不需要class类参数self。
@classmethod调用时需要cls参数(个人理解也就是self参数),@classmethod方法是可以将参数执行之后返回一个初始化的新类
具体可看下面代码理解:
class Add:
@staticmethod
def add(a,b):
c = a+b
print(c)
# return c
class Data_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
@staticmethod
def get_date(cls,string_date):
#这里第一个参数是cls, 表示调用当前的类名
year,month,day=map(int,string_date.split('-'))
date1=cls(year,month,day)
#返回的是一个初始化后的类
return date1
def out_date(self):
print ("year :")
print (self.year)
print ("month :")
print (self.month)
print ("day :")
print(self.day)
if __name__ == "__main__":
print("********************this file is test classmethod and staticmethod**********************")
Add.add(1,2)
Add().add(1,3)
t=Data_test(2016,8,1)
t = Data_test.get_date("2016-8-1")
t.out_date()