The path to Python, 18th: Introduction to Python and Basics 18

Source: Internet
Author: User

Python3 Object-Oriented Programming 2

Class method:

@classmethod

Function: 1, class method is the only way to access class variables;

2, the class method needs to use the @classmethod adorner definition;

3, the first parameter of a class method is an instance of the class, and the Convention is written as CLS

Note: 1, class instances and object instances can call class methods;

2, class methods cannot be method instance variables

Comparison of class methods and instance methods:

1, the class method can access the class variable, cannot access the instance variable;

Instance methods can access class variables and also access instance variables

2, the class method can be invoked with an instance, or it can be invoked with a class;

The instance method must pass in the instance when it is called;

1 classBank:2Moneys = 10000000#10 million3 @classmethod4     defTotal_money (CLS):5         Print("Total capital of a bank:", Cls.moneys)6 7     def __init__(self, b):8Self.branch =b9Self.moneys = 5000000TenSelf.__class__. Moneys-= 5000000 One  A  -Bank.total_money ()#Total capital of a bank: 10000000 -B1 = Bank ("XXX Address sub-branch") theB1.total_money ()#Total capital of a bank: 5000000
View Code

Static methods

@staticmethod

Function: 1, static method is a normal function;

2, the static method is defined inside the class and can only be called by virtue of that class and instance

3, static methods need to be defined using the @staticmethod adorner

4, the static method is the same as the normal function definition, does not need to pass in the self instance parameter and the CLS class parameter;

Description: 1, both class instances and object instances can call static methods;

2, static methods can not method class variables and instance variables;

The path to Python, 18th: Introduction to Python and Basics 18

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.