The difference between a Python class method, a static method, and an instance method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.