Python Object-oriented programming

Source: Internet
Author: User

One: What is the programming paradigm?

Programming is the process by which programmers use a specific syntax + data structure + algorithm to tell a computer how to perform a task.

If the programming process is likened to practicing martial arts, then the programming paradigm refers to the various genres in martial arts, and the two most common genres in the programming world are: process-oriented and object-oriented.

"Kungfu schools do not have high and low points, only the martial arts talents have high and low points", in the programming world is so, oriented process and object-oriented in different scenarios have their pros and cons, who good who bad can not generalize.

A program is a set of instructions that programmers write in order to get a task result, and there are so many different ways to accomplish a task in a way that can be summed up by the characteristics of these different programming styles, that is, the programming paradigm, Different programming paradigms essentially represent different solutions to various tasks, most languages only support one programming paradigm, and of course some languages can support multiple programming paradigms at the same time. Two of the most important programming paradigms are process-oriented programming and object-oriented programming.

Two: What is process-oriented programming?

Process-oriented programming dependent-procedures, a procedure contains a set of steps to be evaluated, the process is called Top-down languages, is the program from the top to the next step, step by step from top to bottom, from start to finish to solve the problem. The basic design idea is that the program starts with solving a big problem, and then breaks down a big problem into many small problems or sub-processes, and the process continues to decompose until the small problem is simple enough to be solved within a small step.

To give a typical process-oriented example, write a remote backup program of data, three steps, local data packaging, upload to the cloud server, test backup file availability.

def cloud_upload (file): Print        ("\nconnecting Cloud storage Center ...")        print ("cloud storage connected.")        Print ("Upload file...xxx. To cloud ... ", file)        print (' Close connection ... ') def data_backup (folder):    print (" Find directory to back up ... ", folder)    Print ("Package the backup file, move to the appropriate directory ...")    return '/tmp/backup20181103.zip ' Def data_backup_test ():    print ("\ n Download the backup file from a remote cloud center from another machine to see if the file is lossless "def main ():    zip_file = data_backup (" c:\\users\\alex\ Europe 100G HD Uncensored ")    Cloud_upload (zip_file)    data_backup_test () if __name__ = = ' __main__ ':    Main ()

This variable, that this sub-process you also want to modify, if there is another subroutine dependent on the sub-process, then there will be a series of effects, as the program becomes larger and higher, the maintenance of this method is more difficult.

Test = 1def cloud_upload (file):    if test = = 1:        print ("\nconnecting Cloud storage Center ...")        print ("cloud Storage connected. ")        Print ("Upload file...xxx. To cloud ... ", file)        print (' Close connection ... ')        return True    else:        print (" No backup ")        return Falsedef data_backup (folder):    print ("Locate the directory to be backed up ...", folder)    print ("Package the backup file, move to the appropriate directory ...")    return '/tmp/ Backup20181103.zip ' Def data_backup_test (upload_res):    if upload_res = = 1:        print ("\ nthe backup file from another machine from the remote cloud Center download, see if the file is lossless ")    else:        print (" Upload error, not backup ") def main ():    zip_file = Data_backup (" c:\\users\\ Alex\ Europe 100G HD Uncensored ")    res = cloud_upload (zip_file)    data_backup_test (res) if __name__ = = ' __main__ ':    Main ( )

So we generally think that if you just write some simple scripts to do some one-off tasks, it's great to use a process-oriented approach, but if the task you're dealing with is complex and needs to be iterative and maintainable, it's the most convenient way to use object-oriented.

Three: Object-oriented Programming primer

You are a game company developer now, you need to develop a game called < dog Wars >, you think about it, the dog fight, that requires at least 2 characters, one is a person, a dog, and people and dogs have different skills, such as a man with a stick to beat the dog, the dog can bite people, How to describe the different roles and their functions?

You've collected all the skills you've mastered and written the following code to describe the two characters

person = {    ' name ': ' Alex ',    ' attack ': +, #杀伤力    ' life_value ': 1000}dog = {    ' name ': ' Peiqi ',    ' attack ' : $, #杀伤力    ' life_value ': 800}

A dictionary represents a role entity, but what if there are multiple dogs and more people playing together? Then you have to write multiple dictionaries.

person = {    ' name ': ' Alex ',    ' attack ': +, #杀伤力    ' life_value ': 1000}person2 = {    ' name ': ' Black Girl ',    ' attack ': #杀伤力    ' life_value ': 600}dog = {    ' name ': ' Peiqi ',    ' attack ': $, #杀伤力    ' Life_ Value ': 800}

This is problematic, because if the value in your dictionary is not carefully defined, and the attack is written in Atteck, then the whole program has a problem. So you quickly come up with an improvement plan to put the dictionary into function

def person (name,attack,life_value):    data = {        ' name ': Name,        ' attack ': attack,        ' life_value ': life_ Value,    }    return datadef dog (name, attack, Life_value):    data = {        ' name ': Name,        ' attack ': attack,        ' Life_value ': Life_value,    }    return Dataalex = person ("Alex", 100,1000) Rain = Person ("Black girl", 80,700) d = Dog ("Peiqi", 200,800)

Well, now that the role is defined, the function of each character, the function of the man to beat the dog, the dog bites people to define

Def attack (P,d): "" "    Man beat Dog Function" ""    d[' life_value ']-= p[' attack '] #被打了, to drop the blood    print ("Man [%s] hit the dog [%s] ... , [%s] has a health value of [%s] "% (p[' name '], d[' name '],d[' name '],d[' Life_value '])) def Bite (d,p):" ""    Dog bite Function "" "    p[" Life_ Value ']-= d[' attack ']    print ("Dog [%s] bit" [%s] ... , [%s] has a health value of [%s] "% (d[' name '], p[' name '],p[' name '],p[' Life_value '])) Alex = Person (" Alex ", 100,1000) Black_girl = person ("Black Girl", 80,700) d = Dog ("Peiqi", 200,800) attack (alex,d) bite (D,black_girl)

But to set a lot of features, do we want to add a little bit? So long special trouble, change this to change that, in order to solve the above problem, we use object-oriented.

Four: What is Object-oriented?

OOP (object oriented programing) programming is the use of "classes" and "objects" to create various models to achieve a real-world description.

What do you say?

The core is the word "object", to understand what the object is, we must regard themselves as God, in the eyes of God, the existence of all things in the world are objects, not exist can also be created. Programmers based on the object-oriented design program is like the Tathagata design to the journey, the Tathagata to solve the problem is to pass the scriptures to the East Earth Datang, the Tathagata did not consider the problem of the solution process, but designed to take charge of the master of four people: Tang Monk, Sha Monk, Pig Eight commandments, Monkey King, responsible for harassment of the Demons and responsible for the escort of the gods, these are all objects, and then the beginning of the study, is the master and the Master Four with ghosts and demons until the completion of the mission. So the object-oriented design program is like creating a world in which the world is made up of objects, and you are the god of the world.

It is not difficult for us to conclude from any of the characters in the journey to the Monkey: objects are the combination of features and skills. For example, Monkey King's characteristics are: hair face thunder mouth, skills are: 72 change, eyes and so on.

It is a kind of "God-like" way of thinking, which is in sharp contrast with the process-oriented mode of thinking, which focuses on the simulation of the real world rather than the process.

Process-oriented = personal perspective
I'm going to big health care, I only need to consider, I have no money, to which store, how to, do what price can, you each step through the program definition, write dead, in this program, you are only set to big health care function, you say halfway I want to go to a KTV, that may lead to the entire program logic has to change. Write the code in a process-oriented way, and your care is the process of executing the whole thing.
Object-oriented = = God Perspective
If you are God, you now want to Genesis, so many people, animals, mountains and rivers made out, God light on their own dry, a one of the creation, how tired, let you do this work, you must be the first mold, a man die, a woman die, the rest of the copy on the line. What is the role of this mold? The mold defines all the characteristics of the human species (or, we classify individuals with these characteristics as human beings). All the things in this world are defined by you, you need the most efficient way to make the world, the most efficient way is to first the world according to species, appearance, life and other dimensions of the classification, and then to each kind of things to model, and then let it in not out of your basic horizontal definition of the framework of self-multiplication (the world is colorful So even the same species, it's a little different.

  

V: Object-oriented and process-oriented advantages and disadvantages vs. process oriented

  Advantages :

    • The complexity of the problem flow, and then simplification (a complex problem, divided into small steps to achieve, the implementation of small steps will be very simple)
    • To give a typical process-oriented example, write a remote backup program of data, three steps, local data packaging, upload to the cloud server, test backup file availability.

  Disadvantages :

    • A set of pipeline or process is used to solve a problem, such as the production line of soda can not produce a car, even if it is able to be big change, change a component, and its related components need to be modified, reaching, very poor extensibility.
    • For example, we modify the function of step two cloud_upload logic, then rely on step two results to normal execution of the function of step three data_backup_test related logic also need to modify, which caused a chain reaction, and this drawback will become more and more bad as the program grows , our procedures will be more difficult to maintain.

  Application Scenarios :

Process-oriented program design ideas are typically used in scenarios where functionality is rarely changed once implemented, and if you're just writing simple scripts to do some one-off tasks, it's great to use a process-oriented approach, with examples of Linux kernel, git, and Apache HTTP server. But if the task you're dealing with is complex and needs to be constantly iterated and maintained, it's the easiest thing to do with object-oriented.

Object oriented

 Advantages:

Solve the problem of low-oriented process scalability, it should be emphasized that, for a software quality, object-oriented programming does not represent all, object-oriented programming is only to solve the extensibility problem.

  Disadvantages:

Programming complexity is much higher than process-oriented, does not understand the object-oriented and immediately get started and based on its design program, extremely prone to over-design problems, and in some of the low-scalability scenarios using object-oriented programming difficulty, such as the management of the Linux system Shell script program is not suitable for object-oriented design, Process-oriented is more appropriate.

  Application Scenarios:

Of course is applied to the requirements of the frequent changes in the software, the general needs of the changes are concentrated in the user layer, Internet applications, enterprise internal software, games, etc. are object-oriented programming is a good place.

VI: Why use object-oriented?
    1. Make your programs more scalable and easy to change, making development more efficient
    2. An object-oriented program can make it easier for people to understand your code logic and make team development easier.
Seven: Object-oriented noun interpretation

class: A class is an abstraction, Blueprint, prototype, template for a class of objects that have the same properties. The properties of these objects are defined in the class (variables (data)), common methods

attributes: human beings contain many characteristics, which are described by programs, called attributes, such as age, height, gender, name, etc. are called attributes, and a class can have multiple properties

methods: Human beings not only have height, age, sex these attributes, but also can do a lot of things, such as talking, walking, eating and so on, compared to the attribute is a noun, talking, walking is a verb, these verbs are described by the procedure is called method.

instance (object): An object is an instantiated instance of a class, a class must be instantiated before it can be called in a program, a class can instantiate multiple objects, and each object can have different properties, just as human refers to everyone, each person refers to the specific object, people and people before there is common, There are also different

instantiation: The process of turning a class into an object is called instantiation

Eight: Object-oriented three major features

1,encapsulation Package

The assignment of data in a class, internal invocation is transparent to external users, which makes the class A capsule or container in which the data and methods of the class are contained.

2,inheritance inheritance

A class can derive subclasses, properties, methods defined in the parent class, automatic quilt class inheritance

3,polymorphism polymorphism

Polymorphism is an important feature of object-oriented, simple point: "An interface, a variety of implementations", refers to a base class derived from a different subclass, and each subclass inherits the same method name, but also the parent class method to do a different implementation, this is the same thing shows a variety of forms.

Programming is actually a process of abstracting the concrete world, which is a manifestation of abstraction, abstracting the common denominator of a series of specific things, and then through this abstract thing, and dialogue with different concrete things.

Sending the same message to different classes of objects will have different behavior. For example, if your boss lets all employees start working at nine o'clock, he says "get started" at nine o'clock, instead of saying to the salesperson: "Start a sales job," say to the technician, "Start technical work", because "employee" is an abstract thing, so long as the employee can start to work, He knows that. As for each employee, of course, they do their job and do their jobs.

Polymorphism allows the object of a subclass to be used as an object of the parent class, a reference to a parent type to an object of its subtype, and the method called is the method of that subtype. The code that references and invokes the method is already determined before it is compiled, and the object pointed to by the reference can be dynamically bound during run time

IX: Common terminology about OPP in Python

9.1 Abstraction/Implementation

Abstract refers to the real world problems and entities of the nature of the performance, behavior and feature modeling, the establishment of a relevant subset, can be used to draw the program structure, so as to achieve this model. Abstractions include not only the data properties of this model, but also the interfaces of the data.

The implementation of an abstraction is the actualization of this data and its associated interfaces (realization). The process of actualization should be transparent and irrelevant to the client program.

9.2 Package/interface

Encapsulation describes the idea of hiding data/information, which provides interfaces and access functions to data properties. The direct access to the data by any client, ignoring the interface, is the opposite of encapsulation, unless the programmer is allowed to do so. As part of the implementation, the client simply does not need to know how the data properties are organized after encapsulation. In Python, all class properties are public, but names can be "confused" to prevent unauthorized access, but that's all there is to prevent. This requires an interface to the data at design time to prevent the client from accessing the encapsulated data attributes through an irregular operation.

Note: Encapsulation is never equal to "hide something that you don't want others to see and maybe modify later."

The real package is, after deep thinking, making good abstractions, giving "complete and minimal" interfaces, and making internal details transparent to the outside

(Note: External transparency means that outside callers can get whatever functionality they want without being fully aware of the internal details)

9.3 Crafting

The synthesis expands the reference to the class, which makes several different classes synthesize into a large class to solve the real problem. Synthesis of an unusually complex system, such as a class composed of other classes, smaller components may also be other classes, data properties and behavior, all together, each other is a "have a" relationship.

9.4 Derivation/inheritance/inheritance structure

Derivation describes a new attribute derived from a subclass that preserves all the required data and behavior in the existing class type, but allows modification or other custom actions without modifying the definition of the original class.
Inheritance describes a way in which a subclass attribute inherits from an ancestor class
The inheritance structure represents the derivation of many "generations", which can be described as a "genealogy", a contiguous subclass, which is related to the ancestor class.

9.5 Generalization/Specialization

Based on inheritance
Generalization means that all subclasses have the same characteristics as their parent classes and ancestor classes.
Specificity describes the customization of all subclasses, that is, what attributes make it different from their ancestor classes.

9.6 Polymorphism and polymorphism

Polymorphism refers to the multiple states of the same thing: water has many different states: ice, steam

The concept of polymorphism indicates how objects are manipulated and accessed through their common attributes and actions, without regard to their specific classes.

The ice, the water vapor, all inherit from the waters, and they all have a method of the same name to become the cloud, but the ice. to Cloud (), and vapor. Cloud () is a very different process, although the methods are all the same

9.7 Introspection/Reflection

Introspection, also known as reflection, shows how an object obtains its own information at run time. If you pass an object to you, you can find out what it is capable of, which is a powerful feature. If Python does not support some form of introspection, the Dir and type built-in functions will be difficult to work properly. And those special properties, like __dict__,__name__ and __doc__.

Ten: Small white easy to make mistakes

1. Object-oriented programming looks tall, so I should be programming to ensure that the entire class, so the written program must be a good program (object-oriented only for those with high scalability requirements of the scene)

2. A lot of people like to say the object-oriented three characteristics (where this comes from, encapsulation, polymorphism, inheritance?) There are too many loopholes, well, for the time being called the three major features, then I am in the object-oriented programming, I must let me define the class of the complete inclusion of these three features, so write is definitely a good program

Good boy, I said the Dragon 18 Palm has 18 palm, then every time you fight with people from the first hand to hit the 18th palm this appears you will be: Face the enemy, you hit the third palm of the other party has fallen, you say, no, you give me up, I have not show finished ...

3. Class has a class property, instance has an instance property, so we define class when we must define a few class properties, what to do, then hard to think, define the more the better

This makes a serious mistake, the sooner the program object-oriented, the sooner the die, why object-oriented, because we want to combine the data with the function, the whole structure of the program is not out, or need to consider the problem you have not figured out a sorta, you began to object-oriented, which led to, you are there to do, Self-thought, defined a bunch of properties, the results are not used later, or can not figure out what should be defined, it has always wanted to, think about the crazy.

You've seen a company that wants to develop a software that starts writing, and it's certainly a frequent meeting and discussion plan.

4. Since this is so troublesome, then I completely free, we do not use object-oriented programming, you Ah, you have a big, you can do it, silly fork.

11: Object-oriented Software development

Many people after learning the Python class mechanism, encounter a production problem, or will be confused, this is actually too normal, because any program development is designed after programming, Python's class mechanism is just a way of programming, If you want to take the class to go and your problem to die, become more ignorant force is divided into minutes, in the past, the development of software is relatively simple, from the analysis of the task to the writing program, and then to the program debugging, can be done by a person or a group. However, with the rapid increase of software size, the problem of software is very complex, there are too many factors to consider, in a software generated errors and hidden errors, unknown errors may reach an alarming degree, which is not fully resolved in the design phase.

So software development in fact a set of norms, we are only a small part of the study, a complete development process, need to clear each stage of the task, in the guarantee of a phase of the correct premise of the next stage of work, called the Software engineering

The object-oriented software engineering consists of the following sections:

1. Object-oriented analysis (oriented, OOA)

The system analysis stage in software engineering requires the analyst and the user to make a precise analysis and express the needs of the users, and to analyze what the software system should do, not how to do it. Object-oriented analysis, in accordance with the concept and method of object-oriented, in the analysis of the task, from the existence of the relationship between things and things, Guinan out the relevant objects (the object's ' characteristics ' and ' skills ') and objects, and will have the same properties and behavior of the object with a class to identify.

Create a demand model that reflects the work situation, at which point the model is sketchy.

2 Object-oriented design (oriented Design,ood)

According to the requirement model formed in the object-oriented analysis stage, the specific design of each part is carried out separately.

The first is the design of the class, and the design of the class may contain multiple hierarchies (leveraging inheritance and derivation mechanisms). Then, the idea and method of program design are proposed based on these classes, including the design of the algorithm.

There is no specific computer language involved in the design phase, but rather a more general description tool, such as pseudo-code or flowchart, to describe

3 Object-oriented programming (oriented Programming,oop)

based on the results of object-oriented design, choose a computer language to write it as a program, which can be Python

4 Object-oriented testing (oriented Test,oot)

before handing over the program to the user, the program must be rigorously tested to find errors in the program and fix it.

A pair-oriented test is tested with an object-oriented approach, using classes as the basic unit for testing.

5 Object-oriented maintenance (object oriendted soft MAINTENANCE,OOSM)

Just as there is a need for after-sales service and maintenance for any product, there are some problems with the software when it is used, or software vendors want to improve the performance of the software, which requires modification of the program.

Because of the use of object-oriented method development program, the use of program maintenance is relatively easy.

Because of the encapsulation of objects, modifying an object has little effect on other objects, and using the object-oriented method to maintain the program greatly improves the efficiency of software maintenance and is highly scalable.

in the object-oriented approach, the first development must be object-oriented programming (OOP), then OOA and Ood have not developed, so the program designer in order to write object-oriented programs, but also to go deep into the field of analysis and design, especially in the field of design, At that time, OOP actually contained two stages of the current Ood and OOP, which were very demanding for the programmer, and many people felt it difficult to master.

Now the design of a large software, is strictly in accordance with the 5 stages of object-oriented software engineering, this 5-stage work is not done by a person from start to finish, but by different people to complete, so the task of the OOP phase is relatively simple. The program writer only needs to write the program in object-oriented language according to the idea that Ood put forward.

Python Object-oriented programming

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.