Python path [Article 5]: Object-oriented programming, Article 5
Object-Oriented Programming mind Orientation
Http://naotu.baidu.com/file/03516c91377d6cad0ded041aa4ce4433? Token = ccaba09527261666 password: Tim
Oriented: process, function, and Object
Process-oriented: Write the base code from top to bottom based on the business logic!
Process-oriented programming disadvantages: each call is overwritten, the code is particularly long, and the code is not reusable. Every time new features are added, all the code is modified! Is there any way to solve the above drawbacks? The function appears.
Function-oriented: encapsulate a function code into a function. You do not need to write it again later. Just call the function!
Function explanation:
Functions can be understood as one function block. You can split a large function into one block and call a function block when using a function!
A function can be understood as a Lego block. You can use these blocks to make up any of the functions you want!
Functions can call functions! The main function is to concatenate and call functions! The function itself cannot be executed by itself. If you do not call the function, it will never be executed!
Object-oriented: Simpler code reuse!
What Is Object-Oriented Programming? That is, all the code is implemented through classes and objects. It is object-oriented programming!
Create classes and objects
Object-Oriented Programming (Object Oriented Programming, OOP, Object-Oriented Programming)
Java and C # support only object-oriented programming, while python is flexible, that is, it supports Object-Oriented Programming and functional programming.
All languages have the following features: encapsulation, inheritance, and polymorphism (polymorphism is not very good in python)
Object-Oriented Programming is implemented through "Classes" and "objects". Therefore, object-oriented programming is actually the use of "Classes" and "objects.
Let's look at the following two examples:
Example 1:
# Method 1 # function def Bar (): print 'bar' def Hello (name): print 'I am % s' % nameBar () Hello ('tianshuai ') # method 2 # create class Foo: def Bar (self): print 'bar' def Hello (self, name ): print 'I am % s' % name # create object objobj = Foo () obj according to class Foo. bar () # execute the Bar method obj. hello ('tianshuai') # execute the Hello Method
That's simple? It must be the first simple. Why? Isn't class simpler? Because our class is not used yet!
Before learning, encapsulate and inherit, the method is simple!
Example 2:Taking a database as an example: Can the common operations of a database be: add, delete, modify, query, add, delete, modify, and query in four ways?
Def fetch (): def modify (): def remove (): def create () # if I want to add a value to the create FUNCTION, are there: # connect to the database hostname, prot, username, password, dbname # Do I Need To save so many things for connection! After the connection, do you want to open the database? # connect to the database hostname, prot, username, password, dbname # Open # operation # disable it. Do you want to add it? Is the modification required? Search required? You need to take a look at the actual functional programming results: def fetch (hostname, prot, username, password, dbname, arg): # connect to the database hostname, prot, username, password, dbname # Open # operation # disable def modify (hostname, prot, username, password, dbname, arg): # connect to the database hostname, prot, username, password, dbname # Open # operation # disable def remove (hostname, prot, username, password, dbname, arg): # connect to the database hostname, prot, username, password, dbname # Open # operation # disable def create (hostname, prot, username, pass Word, dbname, arg) # connect to the database hostname, prot, username, password, dbname # Open # operation # Close every function contains some fields! If you want to parameterize him, do you want to add all of these parameters to the parameter, and you want to pass parameters to him during execution! Fetch (hostname, prot, username, password, dbname, [11,22, 33,44]) modify (hostname, prot, username, password, dbname, [11,22, 33,44]) creremove ate (hostname, prot, username, password, dbname, [,]) crcreate eate (hostname, prot, username, password, dbname, [,]) did I write it to him for every operation!
The above method is implemented through functions, so let's take a look at the following example through object-oriented implementation:
#! /Usr/bin/env python #-*-coding: UTF-8-*-class Db_contrl (object): def _ init _ (self, hostname, port, username, password, dbname): #__ init _ constructor to execute self during instantiation. hostname = hostname self. port = port self. username = username self. password = password self. dbname = dbname def fetch (self): # connect to the database self. hostname, self. port, self. username, self. password, self. dbname # Open # operation # Close def modify (self): # connect to the database self. hostname, self. port, self. username, self. password, self. dbname # Open # operation # Close def create (self): # connect to the database self. hostname, self. port, self. username, self. password, self. dbname # Open # operation # Close def remove (self): # connect to the database self. hostname, self. port, self. username, self. password, self. dbname # Open # operation # Close obj1 = Db_contrl ('1, 1', 80, 'tianshuai', 'shuai', 'testdb') obj1.fetch () obj1.modify () obj1.create () obj1.remove ()
Do I still need to pass parameters when calling methods in the class? No. The most important object-oriented python is encapsulation!
Where are these parameters?
Obj1 = Db_contrl ('1, 1', 80, 'tianshuai', 'shuaige ', 'testdb') I passed these parameters to the class during instantiation, it is encapsulated into self.
For example:
For example, when boj1 calls a create method, the object in obj1 not only stores the parameters of this object, but also a hidden parameter called "Class Object Pointer ",
His role is to tell the object to find a method there! Think about it. If there is no pointer to this class object, does the object know that it was created by the template? I don't know!
And there is no method in the object. The method is stored in the class! For example, each method has self, which means that the obj1 call is equivalent to def create (obj1 )!!!
Compared with functional programming, do I have to upload a lot of parameters every time I call them?
After reading the above example, I thought: if a group of variables are used together in some methods, if function programming is used at this time, these parameters will be passed every time a method is called!
At this time, we need to think of using object-oriented: encapsulate these variables into objects, and directly upload this object each time you call it!
Example 3:
If there is a game, how do I create a role using a function? Are you sure you want to write a lot of functions to implement it? Please take a look at my code!
#! /Usr/bin/env python #-*-coding: UTF-8-*-''' definition: Game role template and basic functions ''' import randomclass Game_pmodel (object ): def _ init _ (self, name, compression Sion, attack = 0, blood = 0, speed = 0): # constructor, name, occupation, and other information self. name = name # define the common field self. sion = sion # define the common field self. attack = attack self. blood = blood self. speed = speed def supershuai (self): self. blood = self. blood + 1000 self. attack = self. attack+ 1000 self. speed = self. speed + 1000 print "\ 033 [32; 1 m call time current blood volume: % s current attack: % s, current speed: % s" % (self. blood, self. attack, self. speed) def add_attack (self): self. attack = self. attack + 300 print "\ 033 [32; 1 m your current attack power is % s \ 033 [0 m" % self. attack def aspirine (self): self. blood = self. blood + 300 print "\ 033 [32; 1 m your current blood volume is % s \ 033 [0 m" % self. blood def detail (self): "" NOTE: details of the current object "temp =" role: % s; occupation: % s; combat capability: % s; blood volume: % s; speed: % s "% (self. name, self. permission Sion, self. attack, self. blood, self. speed) print temp
When I create a role:
Obj1 = Game_pmodel ('Role name', 'oc', attack, 'bloodshot ', 'speed ')
Now let's take a look! Now we have created a real role with its own name, occupation, attack, blood volume, speed, and ,. If you want to write with a function, will it die!
Summary: when creating a dynamic object, you must use a template. When you create a dynamic object, you must use an object-oriented object!
Inheritance
Inheritance is very simple. For example, I now have a role template. I can create an inaccessible role based on this role template. Now I have a requirement, I want to write a warrior template separately.
I can use a lot of repeated items in the class I wrote above. Can I use them? Do I need to write it again? Python provides a simple method to "inherit "!
As mentioned before, python's object-oriented approach allows you to better reuse your code!
#! /Usr/bin/env python #-*-coding: UTF-8-*-class Game_pmodel (object): def _ init _ (self, name, transfer Sion, attack = 0, blood = 0, speed = 0): # constructor, name and occupation information self. name = name # define the common field self. sion = sion # define the common field self. attack = attack self. blood = blood self. speed = speed def supershuai (self): self. blood = self. blood + 1000 self. attack = self. attack+ 1000 self. speed = self. speed + 1000 print "\ 033 [32; 1 m call time current blood volume: % s current attack: % s, current speed: % s" % (self. blood, self. attack, self. speed) def add_attack (self): self. attack = self. attack + 300 print "\ 033 [32; 1 m your current attack power is % s \ 033 [0 m" % self. attack def aspirine (self): self. blood = self. blood + 300 print "\ 033 [32; 1 m your current blood volume is % s \ 033 [0 m" % self. blood def detail (self): "" NOTE: details of the current object "temp =" role: % s; occupation: % s; combat capability: % s; blood volume: % s; speed: % s "% (self. name, self. permission Sion, self. attack, self. blood, self. speed) print tempclass Warrior (Game_pmodel): def weapon (self): self. attack = self. attack + 1000 print "\ 033 [32; + 1000, your current attack power is: % s \ 033 [0 m" % self. attack
In the second class: Warrior, I didn't set the attack field. That's where it comes! Class Warrior (Game_pmodel): inherits the fields and methods of the base class! As follows:
I instantiated a role through the warrior class, but I didn't come here from add_attack? It is inherited, so this is inherited!
Here is a point to mention, "classic class", "New Class", and many inheritance of him! (Python classes can inherit multiple classes. Java and C # can only inherit one class)
Above! Object is a new type. What is the difference! New classes, some of which have been modified and some new features. We recommend that you use "new classes" in the future"
Here, we need to mention the problem of multi-inheritance:
Whether directly or indirectly inheriting the new class, your class is also the new class!
When a class is a classic class, if there are multiple inheritance classes, it will be searched by depth first.
When a class is a new class, if there are multiple inheritance classes, the search will take precedence over the breadth.
Classic category: go firstAClass. If Class A does not exist, continueBClass. If there is any in Class B, continueDClass. If there is any in Class D, continueCClass. If it is still not found, an error is returned.
New category: go firstAClass. If Class A does not exist, continueBClass. If there is any in Class B, continueCClass. If there is any in Class C, continueDClass. If it is still not found, an error is returned.
Note: In the above search process, once found, the search process is immediately interrupted and will not continue to be found.
So the question is, if there are "classic class" and "New Class" in inheritance, who gives priority? See the following code and diagram:
class D(object): def bar(self): print 'D.bar'class C(D): def bar(self): print 'C.bar'class B(D): passclass A(B,C): passa = A()a.bar()
Only in this case is the breadth first!
Summary
Object-Oriented programming is based on the use of classes and objects.
Class is a template, which contains multiple "functions" for use.
The instance (object) created based on the template. The instance is used to call functions encapsulated in the class.
Object-oriented features: encapsulation, inheritance, and polymorphism (polymorphism is not very good in python)
How to Choose functional programming and object-oriented programming? Under what conditions?
This problem does not exist for C # and Java programmers, because the two languages only support Object-Oriented Programming (functional programming is not supported ). But for Python, PHP and other languages, both programming methods are supported at the same time, and the operations that can be completed by functional programming can be implemented by Object-Oriented operations, functional programming is not good (functional programming cannot implement object-oriented encapsulation functions ).
Therefore, in Python development,All use object-orientedOrObject-oriented and Functional Hybrid use
For more information, see:Http://www.cnblogs.com/wupeiqi/p/4493506.html