Python's Way "11th chapter": Python Object-oriented

Source: Internet
Author: User
Tags class definition

Python Object-oriented
    • Beginner's article:

    The origin of program design

Introduction to object orientation and reasons for birth

The composition of object-oriented programs

Three main features of object-oriented

  

First, the object-oriented primary Chapter 1. The origin of the program design;

Transfer from http://www.cnblogs.com/linhaifeng/articles/6428835.html

2. Object-oriented introduction and the cause of birth;

 1) Several ways of programming

We know that programming is divided into process-oriented programming, functional programming, and object-oriented programming, and the code we write when we first touch programming is process oriented;

Process-oriented programming: The core is the process, refers to the steps to solve the problem, such as what to do first what to do, such a design is like a well-designed pipeline, is a mechanical way of thinking;

Advantages: The complexity of the problem flow, and then simplify;

Disadvantage: Almost no extensibility, the program as long as a slight change to contain the whole body;

The design of functional programming: The problem is decomposed into a set of functions that only accept input and produce output, without any internal state that can affect the resulting output. In any case, calling a function with the same parameters will always produce the same result.

Advantages: Logic can be proven, modular, easy to debug, code re-use;

Cons: All data can not be changed, serious occupation of the running resources, resulting in speed is not fast enough

2) About object-oriented programming;

Object-Oriented Programming: The core is the object, object is a combination of features and skills, based on the object-oriented design program is like in the creation of a world, you are the god of the world, the existence of all objects, non-existent can also be created, and the object-oriented mechanical mode of thinking in sharp contrast.

Advantages: To solve the extensibility of the program, the individual modification of an object, will immediately reflect the entire system, such as the game of a character parameter characteristics and skill changes are easy;

Disadvantages: The complexity of programming is high, and can not be like the process-oriented programming pipeline to accurately predict the problem of the processing process and results; object-oriented programs once the object is the interaction between objects to solve problems, even God can not accurately predict the final results;

Application scenarios: frequently changing requirements of the software, the general needs of the changes are concentrated in the user layer, Internet applications, enterprise internal software, games, etc. are object-oriented settings of the good place;

For a software quality, object-oriented programming is only used to solve the extensibility;

          

  3) Reasons for object-oriented birth:

Please refer to the origin of the program design.

3. Object-oriented program composition;

Object-oriented programs contain classes and objects;

  1) What is a class? How do I write a class?

Class definition: Class is the meaning of category, type, is the most important concept of object-oriented design, the class is like a template, the class is a series of objects similar to the characteristics and skills of the Union; For example: Each of us has the same structure (body structure), the same function (eating and drinking), then, We can say that it is created by this class of people.

Classes are written:

# format: class class Name:     def __init__ (self):         Pass    def func1 ():         Pass    def Func2 ():         Pass     . . . . . . # the function inside the class, which we call the method; # the __init__ method means customizing its own unique characteristics to the object.
code to write a class

The role of the class: attribute reference and instantiation;

classPerson:#Define a humanRole =' Person'  #People's role attributes are people    defWalk (self):#people can walk, that is, there is a way to walk        Print("Person is walking ...")Print(Person.role)#View the Role property of a personPrint(Person.walk)#referring to the way people walk, note that this is not the call
Property Reference (class name. Properties)
classPerson:#Define a humanRole =' Person'  #People's role attributes are people    def __init__(self,name): Self.name= Name#each character has its own nickname;            defWalk (self):#people can walk, that is, there is a way to walk        Print("Person is walking ...")Print(Person.role)#View the Role property of a personPrint(Person.walk)#referring to the way people walk, note that this is not the call
instantiation of

The process of instantiation is actually creating the object, we will introduce the object later;

About the self parameter in a class method:

Self: The object/instance itself is automatically passed to the first parameter of __init__ when instantiated, and you can give him an individual name, but the normal person will not do so;

2) What is an object, how the object is generated, and how to use it?

Object definition: Object is a combination of characteristics and skills, for example, everyone can be a human object, all things are so, so the world is the object of all things;

In reality: The existing objects, from the basic characteristics of the object summed up the class;

In the program: existing classes, after the definition of the class, in accordance with the class instance of a specific object;

The creation of the object:

Objects are generated by instantiation of the class, or the class is virtual and the object is real;

classPerson ():#define a class    def __init__(self,name,age): Function properties of a class Self.name=name Self.age= Agedeflike (self,love): Data properties of a classPrint("%s year%s, like%s"%(self.name,self.age,love)) Ren= Person ("Xiao Zhang", 20)#instantiate an object based on person, that is, create an objectRen.like ("Reading")#object invocation method;---------------------The result of the output---------------------------------------------------Xiao Zhang is 20 years old and likes to read books.#The function property of a class is only the special properties of each object, such as each person's name, age is not the same, this is their special property, and the class of data properties, is a public property, that is, everyone can read;
View Code

  

4. Object-oriented three major features;

Object-oriented has three main characteristics: encapsulation, inheritance, polymorphism;

1) encapsulation;

Definition: encapsulation, from its own meaning to understand is to put something in a container to be loaded up. function is to encapsulate a function into a function, convenient to call, and the object-oriented encapsulation is to have some common functions (in the class we call the method) encapsulated in a class, easy to find use, we call the collation; and a layer of meaning is to hide; Set to private.

Core: Encapsulates the relevant functionality into a class and encapsulates the data into an object;

2) succession;

Definition: Inheritance is a way to create a new class that can inherit one or more parent classes (Python supports multiple inheritance), which is also called a base class or superclass, and a new class is called a derived class or subclass.

Subclasses inherit the attributes of the parent class, that is, when a class cannot find a method or variable in its own class, go back to the parent class to look for it, which solves the problem of code reuse ;

Inheritance is divided into single inheritance and multiple inheritance:

classZJK ():#the parent class of the person class    defSport (Self,sport):Print("%s likes%s"%(self.name,sport))classPerson (ZJK):#defines the ZJK class as its own parent class    def __init__(self,name,age): Self.name=name Self.age= AgedefLike (self,love):Print("%s year%s, like%s"%(self.name,self.age,love)) Ren= Person ("Xiao Zhang", 20) Ren.sport ("Play")#when the Ren object calls sport, it is looked up from its own class (person), and if there is no such method in its own class, it goes back to the parent class (ZJK) and calls it. 
single-Instance inheritance
classzjk ():defSport (Self,sport):Print("%s likes%s"%(self.name,sport))classzjk1 ():defEat (self,eat):Print("%s likes%s"%(self.name,eat))classPerson (ZJK,ZJK1):def __init__(self,name,age): Self.name=name Self.age= AgedefLike (self,love):Print("%s year%s, like%s"%(self.name,self.age,love)) Ren= Person ("Xiao Zhang", 20) Ren.eat ("Eat Fruit")-------------------Print Results------------------------------------------------Xiao Zhang likes to eat fruit
Multiple Inheritance Instances

Thus, we can summarize: the order of multiple inheritance, from left to right, a search;

3) polymorphic;

Definition: polymorphism refers to a class of things have a variety of forms;

For example: Animals have many forms: people, dogs, pigs, such as the object of the case is also different;

ImportABCclassAnimal (METACLASS=ABC. Abcmeta):#The same kind of things: animals@abc. AbstractmethoddefTalk (self):PassclassPeople (Animal):#one of the forms of animals: Man    defTalk (self):Print('Say hello')classDog (Animal):#Animal Form Two: the Dog    defTalk (self):Print('say Wangwang')classPig (Animal):#animal Form three: Pig    defTalk (self):Print('say Aoao')
examples of various forms of animals

For example: The file has a variety of forms: text files, executable files;

ImportABCclassFile (METACLASS=ABC. Abcmeta):#Same Kind of thing: file@abc. AbstractmethoddefClick (self):PassclassText (File):#one of the forms of the file: text file    defClick (self):Print('Open File')classExefile (File):#form Two of the file: executable file    defClick (self):Print('Execute File')
examples of various forms of files

Duck Type:

Tease moment:

Python advocates duck type, that is, ' if it looks like, sounds like and walks like a duck, then it's duck ' python programmers usually write programs based on this behavior. For example, if you want to write a custom version of an existing object, you can inherit the object, or you can create a new object that looks and behaves like, but has nothing to do with it, which is typically used to preserve the loose coupling of program components.

A: Use the various ' file-like ' objects defined in the standard library, although they work like files, but they do not inherit the method of the built-in file object

# Both are like ducks, and both look like files, so they can be used as files . class txtfile:     def Read (self):         Pass    def Write (self):         Pass class diskfile:     def Read (self):         Pass    def Write (self):         Pass
View Code

B. In fact, people have been enjoying the benefits of polymorphism, such as Python's sequence type has many forms: string, list, tuple, polymorphism is shown as follows

# str,list,tuple are sequence types s=str ('hello') L=list ([]) T=tuple ((4,5,6)) # we can use S,l,tS.__len__() L without regard to the three types. __len__ () T. __len__ () Len (s) Len (l) Len (t)
View Code

  

Python's Way "11th chapter": Python Object-oriented

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.