What is object-oriented
An object, that is, a specific individual in an abstract class of things. Everything that exists in this world is an object, and it can be created if it doesn't exist.
Compared to process-oriented differences:
- Programming complexity is much higher than the process-oriented, not understanding object-oriented and immediately get started based on its design program, extremely prone to over-design problems. Programs with low extensibility requirements are better suited to process-oriented.
- Unable to process-oriented programming pipelining can accurately predict the problem of the processing process and results, the object-oriented program once the beginning of the interaction between the object to solve the problem, unable to predict the final results.
Application Scenarios:
Changes in the requirements of the software, general requirements are concentrated in the user layer.
Classes and objects
Class, which is the category. Objects are a combination of features and abilities, while classes are a combination of features and skills that are similar in a series of objects.
In the program, there must be a class first, and then there are objects.
Define the basis for the class:
Properties in a class
- Data properties: As long as the objects produced by this class are shared
- Function Properties: A function defined in a class that is bound to an object. is called a method. The special point of a method bound to an object is the one whose call is bound to, and the caller as the first argument, so the function defined in the class should write a parameter self by default.
Interaction between objects
Class A:state =' China ' def __init__ (self,name,hp,strength) Self. Name = Name Self. HP = HP Self. Strength = Strength DefWar(self,enemy): Ememy. HP-= Self. StrengthPrint('%s remaining health value%s '% (ememy.name,ememy. HP)) Class b:state =' USA ' def __init__ (self,name,hp,strength) Self. Name = Name Self. HP = HP Self. Strength = Strength DefWar(self,enemy): Ememy. HP-= self. Strength Print('%s remaining health value%s '% (ememy.name,ememy. HP)) soldier = A(' soldier ',9) criminal = B(' criminal ',5) Soldier. War(criminal)
Inherited
Resolve the reuse of code. A new class can inherit multiple parent classes, which are called base classes or Super classes. The new class is called a derived class or subclass.
Inheriting only one class is called single inheritance. Inheriting multiple classes is called multiple inheritance.
View Inheritance
- Class. __base__ view only the leftmost inherited class
- Class. __bases__ View all inherited classes
Classic class and Modern class
1. Only in the Python2 want $ The new class and the classic class, the unification in the Python3 is the new class
2. In Python2, there is no explicit class that inherits the object class, and the subclass of that class, which is the classic class
3. In Python2, explicitly declaring a class that inherits object, and subclasses of that class, are all modern classes
4. In Python3, whether or not to inherit object, the object is inherited by default, that is, all classes in Python3 are modern classes
Note: If you do not specify a base class, the object class is inherited by default. The object class is the base class for all Python classes and provides some common methods.
Inheritance and abstract abstraction
Abstraction is the literal meaning of extracting a similar or more like department.
The abstraction is divided into two levels: A similar object is first extracted into a class, in which multiple classes are extracted from a parent class.
Inherited
Use the programming language to implement it, based on the results of the abstraction. must first abstract, and then through the way of inheritance to express the abstract structure
Inheritance and re-usability
#例如要分别创建一些猫和狗. You can analyze the similarities between cats and dogs. such as eating, drinking, pulling, and spreading.ClassAnimal:DefEat(self):PassDefDrink(self):PassDefShit(self):PassDefPee(self):PassClassCat(Animal):Def__init__ ' cat ' def cry ' Wang ~ Wang ') c = Cat ( ' fat family's little Skinny Dog ') d1.eat ()
#注: When an instance finds properties and methods, it first looks from the instance and then goes to the parent class until the top-most parent class is found.
#提示: Using existing classes to create a new class, so that the reuse of the existing software part of the set of most of the programming effort, which is often said that software reuse, not only can reuse their own classes, but also inherit others, such as the standard library, to customize the new data types, This is greatly shorten the software development cycle, for large-scale software development, it is of great significance.
Derived
Of course, subclasses can also add their own new properties or redefine them here (without affecting the parent class), and it is important to note that once you have redefined your own properties and have the same name as the parent, you will be able to invoke the new attributes when you call them.
In subclasses, the new function property of the same name, when editing functions within the function, it may be necessary to reuse the same function function in the parent class, should be used to call the normal function, namely: class names. Func (), at this point is the same as calling the normal function, so even the self parameter to pass the value. In Py3, it is recommended to call the properties and methods of the parent class with super ().
Combination and reusability
The important way of software reuse in addition to inheritance there is another way, namely: the combination
A combination refers to a class in which an object of another class is used as a data property, called a combination of classes
Assigns the strength attribute of a class to another instance or to another class.
Combination and inheritance are important ways to make effective use of existing classes of resources. But both concepts and usage scenarios are different,
1. Ways of inheriting
The relationship between the derived class and the base class is established through inheritance, which is a ' yes ' relationship, such as a horse in a white horse and a human being an animal.
When there are many identical functions between classes, extracting these common functions into a base class is better with inheritance, such as teacher is human, student is human
2. Combination of ways
The relationship between classes and classes is set up in a combinatorial way, and it is a ' have ' relationship, such as professors have birthdays, professors teach Python and Linux courses, professors have students S1, S2, S3 ...
When the classes are significantly different, and the smaller classes are the components needed for larger classes, the combination is better
Interface and normalization design interface in Java
- Features of the Java Interface interface:
- 1) is a set of functions, not a function
- 2) The function of the interface is used for interaction, all functions are public, that is, other objects can be manipulated
- 3) interface defines functions only, but does not involve function implementations
- 4) These functions are related, are animal-related functions, but photosynthesis is not suitable to put into the ianimal inside the * *
Why use an interface
The interface extracts a group of common functions that can be used as a collection of functions.
Then let the subclass implement the functions in the interface.
The significance of this is normalization, what is called normalization, that is, as long as it is based on the same interface implementation of the class, then all of these classes produce objects in use, from the usage of the same.
The benefits of normalization are:
Normalization allows the user to not care about what the object's class is, but only needs to know that these objects have some functionality, which greatly reduces the user's difficulty in using it.
Normalization allows high-level external users to handle the collection of objects that are compatible with all interfaces without distinction
2.1: Just like the Universal file concept of Linux, everything can be processed as a file, without concern whether it is memory, disk, network or screen (of course, for the underlying designers, of course, can also distinguish between "character device" and "Block device", and then make a targeted design: to what extent, depending on demand).
Two uses of inheritance
One: Inheriting the method of the base class and making its own changes or extensions (code reuse): In practice, this use of inheritance is not very significant, and often harmful. Because it causes the subclass to be strongly coupled to the base class.
Two: Declare a subclass is compatible with a base class, define an interface class (imitate Java interface), the interface class defines some interface name (that is, the function name) and does not implement the functions of the interface, subclass inherits the interface class, and implements the function in the interface
Principles of inheritance Implementation 1. Inheritance Order
2. Inheritance principle (how Python implements Inheritance)
How python actually implements inheritance, for each class you define, Python calculates a list of method parsing orders (MRO), which is a simple linear sequential list of all base classes, such as
F.mro () #等同于F. MRO [<class ' main. F ';, <class ' main. D ';, <class ' main. B ';, <class ' main. E ';, <class ' main. C ';, <class ' main. A ';, <class ' object ';]
To implement inheritance, Python finds the base class from left to right on the MRO list until the first class that matches the property is found. The construction of this MRO list is implemented by a C3 linearization algorithm. We're not going to go into the math of this algorithm, it's actually merging all of the parent's MRO lists and following three guidelines: 1. Subclasses are checked before the parent Class 2. Multiple parent classes are checked for 3 based on their order in the list. If there are two legitimate choices for the next class, select the first parent class
Methods to call the parent class in a child class
ClassVehicle:#定义交通工具类 country=' China 'Def__init__(self,name,speed,load,power): Self.name=name self.speed=speed self.load=load Self.power=powerDefRun(self): print (' Start ... 'ClassSubway(Vehicle):#地铁def __init__ (self,name,speed,load , power,line): #super (subway,self) is equivalent to the instance itself in Python3 super () equivalent to Super (subway,self) Super ( ). __init__ (name,speed,load,power) self.line=line def run Metro%s Line welcome '%self.line ') Super (Subway,self). Run () class Mobike #摩拜单车 Passline13=subway ( ' China metro ', ' 180m/s ', ' 1000 people/box ', ' electricity ', 13) Line13.run ()
The difference between super () and direct call with parent class name
When you use the super () function, Python continues to search for the next class on the MRO list. As long as each redefined method uses super () and only calls it once, the control flow will eventually traverse the complete MRO list, and each method will only be called once (Note: All properties using Super Call are looked back from the MRO list's current location. Do not look at the code to find the inheritance relationship, be sure to see the MRO list)
Python--7, Object-oriented