1 #-*- encoding:utf-8 -*- 2 3 class Date(object): 4 def __init__(self, year, month, day): 5 self.year = year 6 self.month = month 7 self.day = day 8 9 #实例方法 10 def tomorrow(self): 11 self.day +=1 12 13 #静态方法(缺点:需要写入固定的类方法名Date) 14 @staticmethod 15 def parse_from_string(data_str): 16 year, month, day = tuple(data_str.split("-")) 17 return Date(int(year), int(month), int(day)) 18 19 #类方法(传入cls类本身,无需固定类方法名Date) 20 @classmethod 21 def parse_string(cls, data_str): 22 year, month, day = tuple(data_str.split("-")) 23 return cls(int(year), int(month), int(day)) 24 25 def __str__(self): 26 return "{year}/{month}/{day}".format(year=self.year, month=self.month, day=self.day) 27 28 if __name__ == "__main__": 29 data_str = "2018-6-29" 30 #调用实例方法 31 data = Date(2018,6,29) 32 data.tomorrow() 33 print(data) 34 #调用静态方法 35 print(Date.parse_from_string(data_str)) 36 #调用类方法 37 print(Date.parse_string(data_str))
原文地址:https://www.cnblogs.com/Phantom3389/p/9240860.html
时间: 2024-11-06 03:49:00