1 #-*-encoding:utf-8-*-2 3 classDate (object):4 def __init__(self, year, month, day):5Self.year = Year6Self.month =Month7Self.day = Day8 9 #instance MethodTen defTomorrow (self): OneSelf.day +=1 A - #static method (disadvantage: Need to write a fixed class method name date) - @staticmethod the defparse_from_string (DATA_STR): -Year, month, day = tuple (Data_str.split ("-")) - returnDate (int (year), Int (month), Int (day)) - + #class method (passed in the CLS class itself without a fixed class method name date) - @classmethod + defparse_string (CLS, data_str): AYear, month, day = tuple (Data_str.split ("-")) at returnCLS (int (year), Int. (month), Int (day)) - - def __str__(self): - return "{Year}/{month}/{day}". Format (Year=self.year, Month=self.month, day=self.day) - - if __name__=="__main__": inData_str ="2018-6-29" - #Invoking instance methods todata = Date (2018,6,29) + Data.tomorrow () - Print(data) the #calling a static method * Print(date.parse_from_string (DATA_STR)) $ #Calling class methodsPanax Notoginseng Print(Date.parse_string (DATA_STR))
The difference between a Python class method, a static method, and an instance method