Python static Method class method

Source: Internet
Author: User

The difference between static method and instance method is mainly embodied in two aspects:
1. When calling a static method externally, you can use the "class name. Method Name" way, or you can use the "object name. Method Name" way. The instance method is only in the following way. That is, calling a static method eliminates the need to create an object.
2. When accessing members of this class, static methods allow access only to static members (that is, static member variables and static methods), not to instance member variables and instance methods, and to instance methods without this limitation.
3. The class method can be called by the object, can also be called by the instance, the incoming is the class object, mainly for the factory method, the concrete implementation will be given to the subclass processing
4. The static method parameter does not have an instance parameter of self, and cannot invoke an instance parameter
# Coding:utf-8class Fruit (object):    Version = 1.0  #静态对象    "" "DocString for Fruit" "    def __init__ (self): C4/>super (Fruit, self). __init__ ()        self.color = ' Blue '    def is_clean (CLS):        print Cls.color        return True    @classmethod    def foo (CLS):        #类方法可以被对象调用, can also be called by the instance, the incoming is the class object, mainly for the factory method, the specific implementation of the sub-class processing        Fruit.version + = 1        print cls.color        print ' Calling this method foo () '    @staticmethod    def pish_color ( Color):        #静态方法参数没有实例参数 Self, cannot invoke instance parameter        Fruit.color = Color    def add_foo (self):        fruit.version + = 1if __name__ = = "__main__":    o = Fruit ()    O.is_clean ()    # o.pish_color (' Green ')    # O.foo ()    Fruit.foo ()    # O.add_foo ()    # print O.version    # o.foo ()    # print o.version    # print Fruit.version


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.