python--Object-Oriented Foundation

Source: Internet
Author: User

Overview
    • Process oriented: Write base code from top to bottom according to business logic
    • Function: A function code is encapsulated in a function, it will not need to be repeated later, only the function can be called
    • Object-oriented: classify and encapsulate functions to make development "faster, better and stronger ..."

Process-oriented programming is most easily accepted by beginners, it often uses a long code to achieve the specified function, the most common operation in the development process is to paste the copy, that is: Copy the previously implemented code block to the current function.

123456789101112131415161718 whileTrue:    ifcpu利用率 > 90%:        #发送邮件提醒        连接邮箱服务器        发送邮件        关闭连接    if硬盘使用空间 > 90%:        #发送邮件提醒        连接邮箱服务器        发送邮件        关闭连接    if内存占用 > 80%:        #发送邮件提醒        连接邮箱服务器        发送邮件        关闭连接

Over time, functional programming has been used to enhance the reusability and readability of code, and it has become:

12345678910111213141516 def发送邮件(内容)    #发送邮件提醒    连接邮箱服务器    发送邮件    关闭连接whileTrue:    ifcpu利用率 > 90%:        发送邮件(‘CPU报警‘)    if硬盘使用空间 > 90%:        发送邮件(‘硬盘报警‘)    if内存占用 > 80%:        发送邮件(‘内存报警‘) 

Today we are going to learn a new way of programming: Object-oriented Programming (object Oriented Programming,oop, OO programming)
Note: Java and C # only support object-oriented programming, while Python is more flexible in that it supports object-oriented programming and functional programming

Creating Classes and objects

Object-oriented programming is a way of programming, which requires "classes" and "objects" to be implemented, so object-oriented programming is actually the use of "classes" and "objects".

A class is a template that can contain multiple functions and functions in a template.

Objects are instances created from templates that can execute functions in a class through an instance object

    • Class is a keyword that indicates that classes
    • Create the object, and then add parentheses to the class name

PS: A function in a class The first argument must be self (see more: Encapsulation of the three main attributes of a class) the function defined in the
class is called method

12345678910111213 # Create class class   Foo:             def   Bar ( self ):          Print   ' Bar '      def   Hello ( self , name):          print   ' I am%s '   % name # object created from class Foo obj obj  =   Foo () obj. Bar ()              #执行Bar方法 obj. Hello ( ' Wupeiqi ' )   #执行Hello方法

Eh, do you have a question here? Using functional programming and object-oriented programming to execute a "method" is easier than an object-oriented approach

    • Object-oriented: "Create Object" "Execute method by Object"
    • Function Programming: "Execute function"

Observing the above-mentioned answers is affirmative, then not absolute, and the different scenarios are different for their programming styles.

Summary: Functional application Scenarios--independent and no shared data between functions

Object-oriented three major features

The three major characteristics of object-oriented are: encapsulation, inheritance and polymorphism.

First, the package

Encapsulation, as the name implies, encapsulates the content somewhere and then calls the content that is encapsulated somewhere.

Therefore, when using object-oriented encapsulation features, you need:

    • Encapsulate content somewhere
    • To invoke the encapsulated content from somewhere

First step: encapsulate the content somewhere

Self is a formal parameter, when executing obj1 = Foo (' Wupeiqi ', 18), self equals obj1

When executing obj2 = Foo (' Alex ', 78), self equals obj2

So, the content is actually encapsulated in objects Obj1 and OBJ2, each object has a name and an age attribute, which is similar to saving in memory.

Step two: Call the encapsulated content from somewhere

When the encapsulated content is called, there are two scenarios:

    • Called directly through an object
    • Indirectly called through self

1. Direct invocation of encapsulated content by object

Shows how objects obj1 and Obj2 are saved in memory, so that the encapsulated content can be called according to the Save format: Object. Property name

Class Foo:     def __init__ (self, Name, age):        self.name = name        Self.age = Age obj1 = Foo (' Wupeiqi ', +) print obj1. Name    # Direct call to the Name property of the Obj1 object print obj1.age     # directly calls the Obj1 object's Age Property Obj2 = Foo (' Alex ',) print Obj2.name    # Call the Name property of the Obj2 object directly print Obj2.age     # Call the Age property of the Obj2 object directly

2. Indirectly invoking the encapsulated content via self

When executing a method in a class, the encapsulated content needs to be indirectly called through self

Class Foo:      def __init__ (self, Name, age):        self.name = name        Self.age = Age      def detail (self):        print Self.name        print self.age  obj1 = Foo (' Wupeiqi ', +) Obj1.detail ()  # Python will pass obj1 to the self parameter by default, which is: Obj1.detail ( OBJ1), so, at this point, the internal self = obj1, namely: Self.name is Wupeiqi; Self.age is obj2  = Foo (' Alex ',) Obj2.detail ()  # python defaults to Obj2 is passed to the self parameter, namely: Obj1.detail (OBJ2), so the self = Obj2 inside the method, that is: Self.name is Alex; Self.age is 78

In summary, for object-oriented encapsulation, it is actually using the construction method to encapsulate the content into the object, and then indirectly through the object directly or self to obtain the encapsulated content.

Practice One : output The following information at the terminal

    • Xiao Ming, 10 years old, male, go up the hill to chop Wood
    • Xiao Ming, 10 years old, male, drive to northeast
    • Xiao Ming, 10 years old, male, favorite big health care
    • Lao Li, 90-year-old man, go up the hill to chop Wood
    • Lao Li, 90-year-old, male, drive to Tohoku
    • Lao Li, 90 years old, male, favorite big health care
    • Lao Zhang ...
Functional programming Object-oriented

The above comparison shows that if you use functional programming, you need to pass the same parameters each time the function is executed, if there are many parameters, you need to paste the copy ... , while for object-oriented only need to encapsulate all the required parameters into the current object when the object is created, and then use self indirectly to go to the current object to take the value.

Exercise two : Game Life Program

1. Create three game characters, respectively:

    • Cang Jing, Female, 18, initial combat 1000
    • Tony Wood, Male, 20, initial combat 1800
    • Wave Toto, female, 19, initial combat 2500

2, the game scene, respectively:

    • Bush fights, consumes 200 combat power
    • Self-cultivation, increased 100 combat effectiveness
    • Multiplayer game, consumes 500 combat power
Game LifeIi. Inheritance

Inheritance, the inheritance in object-oriented is the same as the inheritance in real life, that is, the child can inherit the parent's content.

For example:

Cats can: Meow meow, eat, drink, pull, sprinkle

Dogs can: bark, eat, drink, pull, sprinkle

If we were to create a class for both cats and dogs, we would need to implement all of their functions for cats and dogs, as shown here:

Pseudo code

The above code is not difficult to see, eat, drink, pull, and Satan is the function of both cats and dogs, and we are the cat and the dog's class has been written two times. If you use the idea of inheritance, implement as follows:

Animals: Eating, drinking, pulling, spreading

Cat: Meow Meow (cat inherits function of animal)

Dog: Barking (dogs inherit the function of animals)

Code instance

Therefore, for object-oriented inheritance, it is actually the method of extracting multiple classes common to the parent class, and the subclass inherits only the parent class without having to implement each method in one.

Note: In addition to the names of subclasses and parent classes, you may have seen derived and base classes that are only different from subclasses and parent classes.

So the question comes again, how to inherit?

    • Whether multiple classes can be inherited
    • If you have inherited multiple classes that have the same function in each class, then that one will be used?

1. Python classes can inherit multiple classes, and Java and C # can inherit only one class

2. If the class of Python2 inherits more than one class, there are two ways to find the method, namely: depth first and breadth First

    • When a class is a classic class, multiple inheritance cases are searched in the depth-first way
    • When a class is a new class, in multiple inheritance cases, the breadth-first method is found

Classic class and new class, literally can see an old a new, new inevitably contain with many functions, is also recommended after the wording, from the wording of the words, if the current class or the parent class inherits the object class , then the class is a new class, otherwise it is the classic class.

Classical class multi-inherit new type multi-inheritance

Attention:

    • In the above lookup process, once found, the search process immediately interrupted, and will not continue to find
    • For Python3, there are only new classes, that is to say, depth first (special: The structure of the same parent class for the top layer, then this parent is finally found)
    • In multiple inheritance cases, this class belongs to the new class only if each parent class has a common new parent class.

Easy to mistake:

When you look at the source code, you often encounter methods that call other methods, and you need to be aware of who the original object is. The search method also starts with the order in which the object is found.

Three, polymorphic

Pyhon does not support polymorphic notation in strongly typed languages such as Java and C #, but native Polymorphic, whose python advocates "duck type".

Python pseudo-code implements a Java or C # polymorphic python "Duck Type" interface (Supplemental):

Interface is to play a limiting role, the implementation of the interface is similar to the class, but the method can not implement any function, can only create a shell, if a class inherits this interface, then you have to implement (override) all the methods in the interface, otherwise it will be error-free.

What is the actual use of the interface? This has to be multi-state, in many cases the specified type of polymorphism is the base class interface, because once the same subclass of the interface must implement all the methods in the interface, so there is no polymorphic call method does not exist, the situation is not uniform.

Summarize

The above is the introduction of object-oriented primary knowledge in this section, summarized as follows:

    • Object-oriented is a programmatic approach that is implemented based on the use of classes and objects
    • Class is a template that wraps multiple "functions" in a template for use
    • Object, an instance created from a template (that is, an object) used to invoke a function that is wrapped in a class
    • Object-oriented three major features: encapsulation, inheritance, and polymorphism

Question and Answer zone

Question number one: What kind of code is object-oriented?

A: In simple terms, if all the functions in a program are implemented using classes and objects, then object-oriented programming is used.

Question two: How does functional programming and object-oriented selection work? Under what circumstances are they used?

A: This is not a problem for C # and Java programmers because the two languages only support object-oriented programming (functional programming is not supported). And for languages such as Python and PHP, while supporting two programming methods, and functional programming can be done, object-oriented can be implemented, and the object-oriented operation, functional programming is not possible (functional programming can not implement object-oriented encapsulation function).

Therefore, in Python development in general, all use object-oriented or object-oriented and functional mixed use

Object-oriented application scenarios:

      1. multiple functions need to use common values, such as: Database, delete, change, check operations need to connect the database string, host name, user name and password Demo
      2. Multiple things need to be created, each with the same number of attributes, but the need for values
        such as: Zhang San, John Doe, Yang, they all have a name, age, blood type, but it is not the same. That is: The number of attributes is the same, but the values are different. Demo

        Question three: How are classes and objects stored in memory?

        A: classes and methods in the class have only one copy in memory, and each object created by the class needs to be stored in memory, roughly as follows:

        As shown, when you create an object from a class, the object, in addition to encapsulating the value of name and age, holds a class object pointer that points to the class of the current object.

        When "method One" is executed through OBJ1, the process is as follows:

        1. Finds a method in a class based on the pointer to a class object in the current object
        2. Obj1 the object as a parameter to the first argument of the method self

python--Object-Oriented Foundation

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.