Python static Method-class method

Source: Internet
Author: User
Tags python static method

About static methods for classes: @staticmethod and @classmethod

1, use these two methods, do not instantiate class, directly can be used, such as: Stu.say ()

2, the difference between the two methods:

1, @staticmethod do not need to add parameters;

Call class variable with: Class name. class variable name;

Call class function with: Class name. function ()

2, @classmethod need to add parameter cls;

Call class variables with: CLS. class variable name;

Call a class function with: CLS (). function ()

classStu (object): Country=' China'  #class Variables    def __init__(Self, name=' World'): Self.name=name @staticmethod#The static method, which has nothing to do with the class itself, is equivalent to defining a method within the class .    defsay ():Print('Shanghai')        Print(stu.country) Stu ('Static'). Hi () @classmethod#The static method, unlike the class method, is that it can use a class variable and must pass a value that represents the class    defHello (CLS):Print('-------------------------')        Print(Cls.country) Cls.say () CLS (). Hi ()defhi (self):#This is an example method .        Print(Self.name) Stu.say () Stu.hello ()#t = Stu (' name ')#T.hi ()#T.say ()#T.hello ()

Python static Method-class method

Related Article

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.