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: 5000000View 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