Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky
Basic concepts of object orientation
Everything is an object
In Python, all data types are objects, functions are objects, and modules are objects
All Python classes inherit from the most basic object class
The manipulation of data types in Python is all about class methods
Object-oriented programming
Object-oriented Programming is also called OOP (Object-oriented Programming)
- OOP: Object-oriented programming, a programming idea that focuses on highly abstract, reusable code
- OOP treats objects as the basic unit of a program. Objects contain data and functions that manipulate that data
- OOP is essentially the abstraction of problem solving into object-centric computer programs
- OOP is useful in larger or complex projects where OOP can increase collaborative productivity
- The main value of OOP is code reuse
- OOP is simply a programming approach, not a high-level approach to problem solving
The difference between procedural and object oriented
Process oriented to solve the problem of the process steps as the core of the way to write programs, object oriented to problem object construction and application as the core of the way to write programs, all problems that can be solved with OOP, process oriented can be solved.
Object-oriented characteristics
-
Encapsulation: The abstraction of properties and methods, using data and methods for manipulating data to form object logic
-
Method abstraction: Attributes (variables) of a class are defined, isolated, and protected
- Object abstraction: The definition, isolation, and protection of a class’s methods (functions)
- The goal is to form an interface to the class’s externally operable properties and methods
-
-
Inheritance: A high-level abstraction for code reuse that uses inheritance relationships between objects to form code reuse
-
Inheritance is one of the essence of object-oriented programming
- High level of class – based code reuse is achieved
- Inheritance is the process by which a newly defined class can use almost all of the attributes and methods of the original class
-
-
Polymorphism: An abstraction of method flexibility that allows for more flexible manipulation of objects and more reusable code
-
Parameter type polymorphism: The ability of a method to handle multiple types
- Parametric polymorphism: The ability of a method to accept more than one parameter
- Polymorphism is a traditional concept of OOP, and Python naturally supports polymorphism without requiring special syntax
-
Python object-oriented terms
Class (Class) and objects (Object)
-
Classes: Logical abstractions and templates that produce objects, a specific choreography of a set of variables and functions
-
Object: An entity that concretely represents data and operations, equivalent to “variables” in a program. Including: class objects, instance objects
After the class definition is completed, a class object is generated by default, each class corresponds to a unique class object, used to store the tired basic information class object is an instance of Type, expressed as type type;
- Instance objects(Instance Object) : Objects generated after an instance of a Python class
- There is only one class object globally, and multiple instance objects can be generated
-
Properties: “variables” that store data (that is, variables defined in a class) and describe some of the class’s property parameters. Including: class attributes, instance attributes
- Class attribute(Class Attribute) : attributes of a class object, shared by all instance objects; Class defined in
__init__
Outside of the function. In general, attributes that are common to classes are defined as class attributes. - Instance attributes(Instance Attribute) : Attributes of an instance object, usually defined in a function of a class. Instance attributes may be unique to an instance.
- Class attribute(Class Attribute) : attributes of a class object, shared by all instance objects; Class defined in
-
Methods: “methods” that manipulate data (that is, variables defined in a class) to give the class its operational functions. Including: class methods, instance methods, free methods, static methods, reserved methods
- Class method(Class Method) : a method of a class object shared by all instance objects
- Instance methods(Instance Method) : instance object method, by each instance object exclusive, the most common form,
- The free way(Namespace Method) : a common function in a class, managed by the namespace of the class and exclusive to the class object
- A static method(Static Method) : a common function in a class, shared by the object and the instance object
- Save method(Reserved Method) : There are double underline kashgar and end methods, reserved for use.
-
Instantiation: The process from class to object, where all objects are derived from a class
Building Python classes
The basic build of the class
In Python, classes are defined using the class keyword plus the class name, and by indentation we can determine the code block of the class, just as we would define a function. Grammatical structure
Class < class name >: [class description "documentation string"]Copy the code
Because Python is a scripting language, definition classes have no restrictions on their location. They can be included in branches or other dependent blocks, where execution exists
- Class name: Can be any valid identifier, usually with a capital letter
- Class description: The first line after the class definition is defined as a separate string. Pass after definition
The < class name >. __doc__
To access the
The sample code
class TestClass: """ this is a TestClass. """ print("Hello Class Object") print(testclass.__doc__) print(type(TestClass)) ---- ---- Hello Class Object This is a test class <class 'type'>"Copy the code
Statements directly contained in class objects are executed, so defining classes try not to include statements directly in their classes
Instance objects: Instance objects are the most common form of Python classes
Create instance object syntax structure
< object name > = < class name >([parameter])Copy the code
The sample code
Class TestClass: print (" a bowl of weeks ") = TestClass tt () print (type (tt)) ' ' ', the output, a bowl of weeks < class '__main__. TestClass' > ' ' 'Copy the code
Class constructor
concept
- Class constructors are used in the process of creating instance objects from a class
- Class constructor provides input parameters for instance object creation
- Class constructors provide support for defining and assigning instance attributes
Python uses the predefined __init__() constructor
Grammatical structure
Class class name: def __init__(self,[parameter 1],[parameter 2],... [parameter n]): < statement block >...Copy the code
The sample code
Class __init__(self, name): def __init__(self, name): print(name) text1 = test1 (" 三") #Copy the code
The __init__ constructor provides arguments to Python
**__init__()** instructions
Arguments: The first argument convention is self, which represents the class instance itself. The other arguments are instance arguments (self is used internally and is reserved by default. Other user-input arguments are placed after self).
Function names: Defined internally by the Python interpreter, beginning and ending with a double underscore (__)
Return value: The constructor returns no value or None, otherwise TypeError is raised
**self** represents the instance of the class inside the class definition
slef
Is a class parameter specified by the Python object-oriented conventionself
Represents an instance of a class, inside the class,self
Properties and methods used to combine access instances- In contrast, the class name represents the class object itself
Attributes of a class
Attributes are variables defined within a class and are syntactic ↓
Def __init__(self,[parameter 1],[parameter 2],... [parameter n]): self.< instance attribute name > = < instance attribute initial value >...Copy the code
- Access class attributes:
< class name >.< class attribute >
or< object name >.< Class properties >
- Access instance properties:
< object name >.< Instance Properties >
The sample code
Class TestClass: count = 0 def __init__(self, name, age): Self. name = name self.age = name TestClass. Count += 1 Students2 = TestClass(" 表 ", "表 ") print(" 表 ", testclass.count) # Students2.name = students2.name = students2.name = students2.name = students2.name = students2.name = students2.name = students2.name = students2.nameCopy the code
Methods of a class
-
Instance methods: Instance methods are internal class defined functions, independent of the instance object, syntactic structure
Class ClassName: def < method name >(self, < argument list >):...Copy the code
< method name >(< parameter list >) is used to define the instance method. The first argument is self
The sample code
class TestClass: def __init__(self, number): self.number = number def sum_number(self): Sum_num = 0 for I in range(self.number + 1): Sum_num += I return sum_num number1 = TestClass(100) number2 = TestClass(10) print(number1.sum_number()) # 5050 print(number2.sum_number()) # 55Copy the code
-
Class methods: Class methods are functions related to class objects that are shared by all instance objects
Class ClassName: @classmethod def < ClassName >(CLS, < parameter list >):...Copy the code
< method name >(< parameter list >) or < class name >.< method name >(< parameter list >). A classmethod contains at least one parameter that represents the class object
Class methods can only operate on class properties and other class methods, not instance properties and methods.
The sample code
class TestClass: sum_num = 0 def __init__(self, number): self.number = number def sum_number(self): for i in range(self.number + 1): Sum_num += I return testclass.sum_num @classmethod def test(CLS): Sum_num * 2 return test_value value1 = TestClass(100) print(value1.sum_number()) # 5050 print(value1.test()) # 10100Copy the code
-
Private methods: Private methods are ordinary functions defined in the class namespace. The syntax is as follows:
Class ClassName: def < method name >(< parameter list >):...Copy the code
.< method name >(< parameter list >), < class name > denotes the namespace. Your own methods don’t need arguments like self or CLS, they can have no arguments. Own methods can only operate on class properties and methods, not instance properties and methods. Free methods can only be used with < class name >
A free method is not strictly a method, but a function defined in a class
The sample code
class TestClass: sum_num = 0 def __init__(self, number): self.number = number def sum_number(self): Sum_num += I return testclass.sum_num def test(): Sum_num * 2 return test_value def test_out(): Sum_num * 2 return test_out_value value = TestClass(100) print(value.sum_number()) # 5050 print(TestClass.test()) # 10100 print(test_out()) # 10100Copy the code
Free methods defined in a class can also be defined outside
-
Static methods: Ordinary functions defined in a class that can be shared by all instance objects
Class class name: @staticMethod def < staticMethod > : class class name: @staticMethod def < staticMethod > :Copy the code
.< method name >(< argument list >) or < class name >.< method name >(< argument list >) using static methods can also have no arguments, which can be understood as its own method that can be called using the object name. @staticmethod is a decorator that is required for staticmethod definitions. Static methods, like free methods, can only manipulate class properties and methods, not instance properties and methods, via < class name > or < object name >.
The sample code
class TestClass: sum_num = 0 def __init__(self, number): self.number = number def sum_number(self): for i in range(self.number + 1): Sum_num += I return testclass.sum_num @staticMethod def test(): test_value = TestClass.sum_num * 2 return test_value value = TestClass(100) print(value.sum_number()) # 5050 print(TestClass.test()) # 10100 print(value.test()) # 10100Copy the code
-
Reserved methods: There are double underline kashi and end methods, reserved for use. Grammatical structure ↓
Class ClassName: def < reserved method name >(< parameter list >):...Copy the code
Reserved methods typically correspond to some type of operation of a class that is called when the operator is used by a reserved method in the Python interpreter