python-one of the object-oriented

Source: Internet
Author: User

First, what is object-oriented programming

OO programming (Object Oriented programming), or OOP, is a programming idea. OOP takes objects as the basic unit of a program, and an object contains functions for data and manipulating data.

Process-oriented programming is to treat a computer program as a series of command sets, that is, the sequence of a set of functions executed. In order to simplify the program design, the process will continue to cut the function into sub-function, that is, the large function by cutting into small block function to reduce the complexity of the system. 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.

Object-oriented programming is to treat a computer program as a collection of objects, and each object can receive messages from other objects and process them, and the execution of a computer program is a series of messages passing between objects.


    • 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 ..."
II. 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".

Class: Equivalent to a template, templates can contain multiple functions, functions in the implementation of some functions.

Object: A function in a class can be executed by an instance object, based on the instance called by the template "class".

# Create class foo:         def Bar (self):        print ' bar '     def Hello (self, name):        print ' I am%s '%name # creates an object from class Foo Objob j = Foo () obj. Bar ()            #执行Bar方法obj. Hello (' Kirusx ') #执行Hello方法
    • Class is a keyword that indicates that classes
    • The first argument of a function in a class must be self, which represents the current instance itself
    • Create the object, and then add parentheses to the class name
    • A function defined in a class is called a "method"
Three main characteristics of object-oriented

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

1. Encapsulation

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

The role of encapsulation:

    • Prevents object data from being arbitrarily modified
    • So that external programs do not need to focus on the internal structure of the object, only through the interface provided by this object directly access to

When using object-oriented encapsulation features, you need:

    • Encapsulate content somewhere
    • To invoke the encapsulated content from somewhere
First step: encapsulate the content somewhere
Class Foo:     def __init__ (self, Name, age):        # called construction method, automatically executes when object is created according to class = name        Self.age = age# Create an object based on class Foo # automatically executes the __init__ method of the Foo class obj1 = foo (' Kirusx ')        # encapsulates Kirusx and 25 respectively into the name and age properties of the obj1 (self)
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

Class Foo:     def __init__ (self, Name, age): = name        Self.age = Age obj1 = Foo (' kirusx ', +) print obj    # Direct call to the Obj1 object's Name property print Obj1.age     # Call the Obj1 object's age property directly

2. Indirectly invoking the encapsulated content via self

When you execute a method in a class, you need to indirectly invoke the encapsulated content through self.

Class Foo:      def __init__ (self, Name, age): = name        Self.age = Age      def detail (self):        print (        print (self.age)  obj1 = Foo (' kirusx ', +) Obj1.detail ()  # Python will pass obj1 to the self parameter by default, That is: Obj1.detail (obj1), so, at this point, the internal self = obj1, that is: is Kirusx;self.age is 25

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.

Example one:

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
#-*-Coding:utf-8-*-# ##################### defines the class #################### #class person:def __init__ (self, Na, Gen, Age, fig): = na Self.gender = Gen Self.age = Age self.fight =fig def grassland (s ELF): "" "Note: Bush fights, consumes 200 combat effectiveness" "" "" Self.fight = self.fight-200 def Practice (self): "" "Note: 100 increase in combat effectiveness "" "Self.fight = self.fight + def incest (self):" "" Note: Multiplayer, consumes 500 combat effectiveness "" " ght = self.fight-500 def detail (self): "" "Comment: Details of the current object" "temp =" Name:%s; Gender:%s; Age:%s; Fighting capacity:%s "% (, Self.gender, Self.age, self.fight) Print (temp) # ##################### start Game ####### ############# #cang = person (' Cang Jing ', ' female ', 18, 1000) # Create Cang jing Role dong = person (' Tony Wood ', ' man ', 20, 1800) # create Tony Wood character Bo = person ( ' Bo Toto ', ' female ', 19, 2500 # Create wave toto character cang.incest () #苍井空参加一次多人游戏dong. Practice () #东尼木木自我修炼了一次bo. Grassland () #波多多参加一次草丛战斗 # outputs the current Someone's details cang.detail () dong.detail () BO.DEtail () cang.incest () #苍井空又参加一次多人游戏dong. Incest () #东尼木木也参加了一个多人游戏bo. Practice () #波多多自我修炼了一次 # Output Details of the current owner Cang.detail ( ) Dong.detail () Bo.detail ()
2. Inheritance

In OOP programming, when we define a class, we can inherit from an existing class, the new class is called a subclass (subclass), and the inherited class is called the base class, the parent class, or the superclass (base classes, Super Class).

For example, we need to write a class called Cat, and a class named dog that has some of the same functions, such as eating, drinking, pulling, spreading, and sleeping. But they also have different places, such as calls. Therefore, we can define this:

Class Animal:    def Eat (self):        print ("%s eat"    def drink (self):        print ("%s drink"    def shit (self):        print ("%s pull"    def pee (self):        print ("%s scatter"    def sleep (self):        Print ("%s Sleeps" class Cat (Animal):    def __init__ (self, name): = name        Self.breed = ' Cat '    def Cry (self):        print (' Meow meow ') class Dog (Animal):        def __init__ (self, name): = name        self.breed = ' dog '            def cry (self):        print (' barking ') # ######### perform ######## #c1 = Cat (' Small White House's little Black Cat ') () C2 = Cat ( ' Little black Little White Cat ') c2.drink () D1 = Dog (' Fat House's Little Skinny Dog ') ()

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.

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 Python class inherits more than one class, there are two ways to find the method: 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, the new must contain with many functions, but also after the recommended wording, from the wording of the words, if the current class or the parent class inherits the object class , Then the class is the new class, otherwise it is the classic class.

Classic Class Inheritance:

Class D:    def bar (self):        print ( class C (d):    def Bar (self):        print ( class B (D):    def Bar ( Self):        print ( Class A (B, C):    def Bar (self):        print ( a = A () # when executing the Bar method # First go to Class A to find, if not in Class A, Then continue to find in class B, if there is a class B, then continue to find in Class D, if there is a class D, then continue to find in class C, if still not found, then error # So, look in order: A-----------and C # in the process of finding the bar method, once found, The search process is immediately interrupted and no further () will be found.

New class Inheritance:

Class D (object):    def Bar (self):        print ( class C (d):    def Bar (self):        print ( class B (d):    def bar (self):        print ( class A (B, C):    def Bar (self):        print ( a = A () # when executing the Bar method # First go to Class A to find, if not in Class A, Then continue to find in class B, if there is a class B, then continue to find in Class C, if there is a Class C, then continue to find in class D, if still not found, then error # So, look in order: A------and C--and d# in the process of finding the bar method above, once found, The search process is immediately interrupted and no further () will be found.

Classic class: First go to a class to find, if not in Class A, then continue to go to class B , if not in class B, then continue to find in class D , if not in Class D, then continue to the class C to find , if it is still not found, the error

New class: First go to class a to find, if not in Class A, then continue to go to Class B , if not in class B, then continue to the class C , if not in Class C, then continue to find in class D , If it is still not found, the error

Note: In the above lookup process, once found, the search process immediately interrupted, and will not continue to look for.

3. polymorphic

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.

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 Java or C # polymorphism:

Class F1:    passclass S1 (F1):    def Show (self):        print ' ' class S2 (F1):    def Show (self):        print ' ' # Because of defining function parameters in Java or C #, you must specify the type of the parameter # in order for the Func function to execute the Show method of the S1 object, and to execute the Show method of the S2 object, the parent class of the S1 and S2 classes is defined # The actual parameters passed in are: S1 object and S2 object def Func (F1 obj):    "" "Func function needs to receive a F1 type or F1 subclass of type" "" "        print ()    s1_obj = S1 () func (s1_obj) # Pass in the S1 class object S1_obj in the Func function, execute S1 's Show method, result: S1.shows2_obj = S2 () func (s2_obj) # passed in the Func function to the SS class object Ss_obj, performing the SS show method, Result:

Python "Duck Type":

Class F1:    passclass S1 (F1):    def Show (self):        print ( class S2 (F1):    def Show (self):        print ( def Func (obj):    

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

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

A: This problem does not exist 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. Extracting public functions

We can extract some of the public functions and create properties of this object in public functions, and then other methods can use the properties of this object.

Let's take a remote upload, execute the command example, the example code is as follows:

def upload ():    #连接服务器    #上传文件    #关闭 def cmd ():    #连接服务器    #执行命令    #关闭

As can be seen from the above, connecting the server and shutting down the service is a common function, we use object-oriented implementation as follows:

Class SSH:         def __init__ (self,host,port,pwd,username):  = host ...           .     def connection (self):           #去创建连接           self.conn = #和服务器创建的连接对象 ()     def close (self):           #关闭            self.conn.     def upload (self):            self.conn #使用连接上传文件     def-cmd (self):            self.conn #使用连接执行命令 obj = SSH (...) obj = connection () obj.upload () Obj.close ()

2, according to a template to create something

We use object-oriented, in fact, is to create a template, for example, see a person class, through this person class to instantiate many objects, subclasses inherit it, you can reuse some properties and methods, there is not much to say.

3. Multiple functions pass in common parameters

  When a lot of functions need to have common parameters, can be extracted from the parameters, encapsulated in the object, convenient for later use. For example, we have a lot of functions that require common parameters, and the code is as follows:

def f1 (Host,port,pwd,arg):    pass def F2 (HOST,PORT,PWD,ARG,ARG2):    Pass def f3 (HOST,PORT,PWD,ARG,ARG2):    Pass

The above three functions are used in the host, Port, PWD, arg four parameters, then we can encapsulate into the object, the code is as follows:

Class F:         def __init__ (self,host,port,pwd,arg):   = host            Self.port = port            self.pwd = pwd            Self.arg = arg             def f2 (self):   ...             .     def f2 (SELF,ARGS2):   ...            .         def f3 (SELF,ARGS2):   ...            .

python-one of the object-oriented

Related Article

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: 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.