UltraMar1ne 2022-05-22 12:23:52 阅读数:36
Object oriented programming is a programming architecture . A basic principle of object-oriented is that computer programs are composed of a single unit or object that can act as a subroutine , These objects are also called models .
Object oriented programming as a new idea , Its essence is the abstract thinking process and object-oriented method embodied by the establishment of models . It is impossible for a model to fully reflect all the specific characteristics of a class of things , Instead, we can only abstract its characteristics and change laws 、 fitting , So as to make it more objective 、 universality .
like , If we have a bird , It is impossible for us to extract all its biological characteristics and biological behavior from a biological point of view ; But we can extract its representative features , Let these characteristics be the basic characteristics that can express its general law . such as , Birds have wings 、 beak 、 Claw , And can fly, etc .
So in the traditional process oriented coding process , We want to implement some kind of complex or advanced function （ For example, realize the calculation of complex numbers ） You'll be stretched out when you ： When the code size is small , In fact, the efficiency of process oriented coding and object-oriented coding is very similar , Even by comparison , The overall architecture of code with object-oriented idea will appear relatively redundant . These redundancy may not play its real role in the early stage , therefore , We might as well wait until it is really useful .
Compared with the traditional process oriented coding , Object oriented thinking has these three characteristics ： encapsulation 、 Inheritance and polymorphism . The following is a specific code example （ With Python Language is the foundation ） For everyone to do more in-depth 、 Image explanation , At the same time, it will also integrate into my own personal understanding ：
Encapsulation refers to the integration of data in a computer system and all operation languages related to this data （ That is, the program code that describes the properties and behavior of each object ） Put it together , Encapsulated in an organic entity , Encapsulate them in a “ modular ” in （ It's actually in the class ）.
The above quotation is the authoritative explanation given by Baidu Encyclopedia . Of course , Part of the explanation is like this ：
Encapsulate a common class , Is to add modifiers to its variables to restrict access , It can be accessed freely inside this class , However, external access can only be realized through the interface provided by this class （ Such as getter and setter Method ）.
In fact, several statements have their own reasons , Here is my own opinion ：
Encapsulation is a process , It is nothing more than abstracting some features from all objectively interpreted laws and extracting , And then combine them , Become a new whole , This process is called abstraction . But for our abstract properties or methods （ If not specified below, they are collectively referred to as ” member “）, Just putting them there will inevitably lead to some problems , For example, the member variables in a class are tampered with at will 、 There is a serious problem with the business logic of a member method, and so on , So we need to restrict their access at this time , The process of making restrictions is called encapsulation .
It may be a little long , Everyone will be confused , In a nutshell ： encapsulation = abstract + Access restrictions . In fact, this is also the case in future study , Abstracting complex concepts into a simple and clear mathematical formula is also an efficient way of understanding .
Then I learned the following content C++、Java Your friends may be very familiar with . Since you want to decorate the members , So how to modify it ？ In the class C In language , Nothing more than adding an access modifier ,public、protected、private wait . however , Because our tutorial is based on Python Language , It may be a little different here , But it's also very simple , Compare Python It is characterized by simplicity .
First of all, it is necessary to explain the differences between these types of modifiers ：
Descriptions of these three types of modifiers are as follows ：
There may be a misunderstanding here ： Consider variables without modifiers to be public Of , This is in class C There are serious mistakes in language , Take a look at the following Python How is it defined in ？
stay Python in , How do we encapsulate members ？ It is also these three kinds of modification relations , But the syntax of modification is simply changed ：
|Access Modifiers||Prefix of members|
From the above table, it is easy to see ,Python It is simplified to the prefix of member identifier . If the member is public , Without any prefix （ The prefix here refers to the underscore ）; If the member is protected , Add an underscore before its identifier ; Private members can be prefixed with two underscores .
Because of the existence of encapsulation , The complexity of program operation is greatly reduced , At the same time ” High cohesion 、 Low coupling “ Design concept of .
In fact, inheritance is easy to understand from the name alone . First, let's look at the authoritative explanation ：
Inheritance mainly refers to the connection and difference between two or more classes . Inheritance is not just the continuation of some characteristics of the former by the latter , It refers to some unique characteristics of one object to another 、 Ability to replicate or continue .
In fact, combined with some common sense in our daily life, it is also very easy to understand ： Children may inherit many characteristics of their parents from their parents , But these characteristics are not invariable , But will change with the growth of offspring 、 Keep updating and iterating , Finally, the process of turning it into a characteristic of one's own .
This argument is actually very well certified in object-oriented thinking ： For the parent class , Subclasses can inherit the members of the parent class , The method is also good , Variables, too , Can be inherited . But there may be such a situation ： For a particular member method , Subclasses don't just want to inherit from their parent class , But through their own... After inheritance ” Reprocessing “, Add its own logic belonging to the subclass , So as to turn it into its own member method . This process is inheritance .
Of course , This ” Reprocessing “ The process of is not necessary , This needs to be analyzed in combination with the actual situation .
Take a chestnut ：
# ！/usr/bin/env python # -*- encoding: utf-8 -*- """ @Author : UltraMarine @File : main.py @Time : 2021/7/25 17:36 @Software: PyCharm 2021.1 x64 """ class A: def __init__(self): print('__init__ method from A') class B(A): def __init__(self): super(B, self).__init__() if __name__ == '__main__': B()
Through the code above , We can create a class B Inherited from A,B The constructor of is completely inherited from its parent class A, So in instantiation B when , Calling its constructor actually calls its parent class directly A Construction method of ：
You can also change the parameter list of the method to be inherited by subclass 、 Method body, etc ：
class B(A): def __init__(self): super().__init__() print('__init__ method from B')
So when instantiating , The result of the operation is ：
stay Python in , There are three situations when subclasses execute construction methods ：
__init__Method , When instantiating a subclass , Will automatically call the parent class definition
__init__Method , When instantiating a subclass , Will not call the parent class
__init__Method , But you want to inherit the constructor of the parent class , have access to
super( Subclass name , self).__init__( Parent class parameter list )Inherit
First, let's look at the official explanation ：
Program runtime , The same message may be sent to multiple objects of different categories , And the system can be based on the category of the object , Raise the method of the corresponding category , And there are different behaviors . Simply speaking , Polymorphism means that the same message given to different objects will cause different actions .
In fact, it's easier to understand , I understand that ： In the actual project , Data requirements are not static , A set of interfaces may only achieve most of the requirements , However, another part of the demand will be shelved because it cannot be processed . So in order to solve the problem of inconsistent resources , Whether different methods can be called by judging the different incoming parameters , This is polymorphism .
Polymorphism can be divided into variable polymorphism and function polymorphism . Variable polymorphism refers to ： Variables of base type （ about C++ Is a reference or pointer ） Can be assigned a base type object , It can also be assigned to objects of derived types . Function polymorphism refers to , The same function call interface （ Function name and argument table ）, Passed to an object variable , Can have different behaviors , This depends on the type of object the object variable points to . therefore , Variable polymorphism is the basis of function polymorphism .
Of course , in my opinion , Polymorphism should be viewed from two perspectives .
First , As mentioned above , Methods that support different parameters and functions use the same method name . This increases the flexibility and scalability of the program , It's something that traditional process oriented programming can't experience .
Then there is the inheritance polymorphism to be mentioned next . Directly speaking, it may be very abstract , Here's an example ： I started by defining a superclass
Bird, We might as well combine it with our daily life , This
Brid Class actually has many derived classes , For example, I can also create its derived classes below
duck wait , The code example is as follows ：
# ！/usr/bin/env python # -*- encoding: utf-8 -*- """ @Author : UltraMarine @File : main.py @Time : 2021/7/25 17:36 @Software: PyCharm 2021.1 x64 """ class Bird: def __init__(self): pass class Chicken(Bird): def __init__(self): super(Chicken, self).__init__() class Duck(Bird): def __init__(self): super(Chicken, self).__init__() ...
This shows that a base class can have multiple subclasses , Its derivation - Inheritance forms a huge network .
Actually in Python In bag , To facilitate the management of modules , I may use this class in the global package
__init__.py in .
perhaps , My package itself is a collection of modules , You can go to
__init__.py Import all these modules into , Then you can directly reference this package ~~
copyright：author[UltraMar1ne]，Please bring the original link to reprint, thank you. https://en.javamana.com/2022/142/202205211828223554.html