Python object oriented programming
There are three common programming methods:
Process oriented: write the base code from top to bottom according to the business logic. The most common operation is paste and copy, and copy the previously implemented code blocks to the existing functions.
Functional: encapsulate a function code into a function. In the future, there is no need to write it repeatedly, just call the function.
Object oriented: classify and encapsulate functions to make development faster, better and stronger.
Compared with Java and C# which only support object-oriented programming, python is more flexible. It supports not only process oriented programming, but also functional programming and object-oriented programming.
Generally, in Python development, object-oriented and functional are usually mixed. Today, we will focus on Python's object-oriented programming.
Create classes and objects
The implementation of object-oriented programming needs to use "class" and "object". Therefore, object-oriented programming is actually the use of "class" and "object".
A class is a template. The template can contain multiple functions to implement different functions. These functions are also called "methods". The first parameter of the function in the class must be self;
Object is an instance created according to the template, through which the functions in the class can be executed.
Contrast: implement a "method" using functional programming and object-oriented programming
- Object oriented: [create object] – > [execute method through object]
- Function programming: [execute function]
It is found that functional programming seems to be simpler, but it is not absolute. The application scenario of functional programming is that each function is independent and has no shared data. The application scenarios of object-oriented programming are:
1) Multiple functions use common values. For example, the database string, host name, user name and password are required for the addition, deletion, modification and query of the database;
2) You need to create multiple things. Each thing has the same number of attributes but different values.
Three characteristics of object oriented
The three characteristics of object-oriented are encapsulation, inheritance and polymorphism.
Encapsulation, as the name suggests
① Encapsulate content somewhere,
② Call the encapsulated content later.
Step 1: encapsulate the content somewhere
self is a formal parameter.
When obj1 = Foo('wupeiqi ', 18) is executed, self is equal to obj1;
When obj2 = Foo('alex ', 78) is executed, self is equal to obj2.
In fact, the content is encapsulated into objects obj1 and obj2. Each object has name and age attributes.
Step 2: call the encapsulated content from somewhere
When invoking encapsulated content, there are two situations:
- Outside the class, after instantiating the object, it is called directly through the object
- In a class, when a function is executed, it is called indirectly through self
1. Outside the class, after instantiating the object, pass the object Property name called directly
class Foo: def __init__( self , name, age): self.name = name self.age = age obj1 = Foo('wupeiqi', 18) print(obj1.name) # Directly call the name attribute of obj1 object print(obj1.age) #Directly call the age attribute of obj1 object
2. In the class, when the function is executed, it is called indirectly 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' , 18 ) obj1.detail()
Python passes the instantiated object (obj1) to the self parameter by default, so self = obj1 inside the method, that is, self Name is wupeiqi; self.age is 18.
Exercise 1: output the following information at the terminal
Xiao Ming, 10 years old, male, went up the mountain to cut firewood
Drive to the northeast, Xiaoming, male, 10
Xiao Ming, 10 years old, male, loves big health care best
Lao Li, 90, male, went up the mountain to cut firewood
Lao Li, 90, male, drove to the northeast
Lao Li, 90 years old, male, loves big health care best
class Foo: def __init__(self, name, age ,gender): self.name = name self.age = age self.gender = gender def kanchai(self): print "%s,%s year,%s,Go up the mountain to cut firewood" %(self.name, self.age, self.gender) def qudongbei(self): print "%s,%s year,%s,Drive to the Northeast" %(self.name, self.age, self.gender) def dabaojian(self): print "%s,%s year,%s,Love big health care" %(self.name, self.age, self.gender) xiaoming = Foo('Xiao Ming', 10, 'male') xiaoming.kanchai() xiaoming.qudongbei() xiaoming.dabaojian() laoli = Foo('Lao Li', 90, 'male') laoli.kanchai() laoli.qudongbei() laoli.dabaojian()
def kanchai(name, age, gender): print "%s,%s year,%s,Go up the mountain to cut firewood" %(name, age, gender) def qudongbei(name, age, gender): print "%s,%s year,%s,Drive to the Northeast" %(name, age, gender) def dabaojian(name, age, gender): print "%s,%s year,%s,Love big health care" %(name, age, gender) kanchai('Xiao Ming', 10, 'male') qudongbei('Xiao Ming', 10, 'male') dabaojian('Xiao Ming', 10, 'male') kanchai('Lao Li', 90, 'male') qudongbei('Lao Li', 90, 'male') dabaojian('Lao Li', 90, 'male')
It can be seen that if you use functional programming, you need to pass in the same parameters every time you execute the function. If there are many parameters, you need to paste and copy;
For object-oriented, you only need to encapsulate all the required parameters into the current object when creating the object, and then use it again by indirectly taking values from the current object through self.
Inheritance, in fact, is to extract the methods shared by multiple classes into the parent class. The child class only needs to inherit the parent class without implementing each method one by one.
Note: in addition to the appellation of subclasses and parent classes, you may have seen derived classes and base classes. They are just different from subclasses and parent classes.
Cats can: meow, eat, drink, pull and scatter
Dogs can: bark, eat, drink, pull and sprinkle
If we want to create a class for cat and dog respectively, we need to implement all their functions for cat and dog.
However, eating, drinking, pulling and scattering are the functions of both cats and dogs. If the idea of inheritance is used, it can be realized as follows:
Animals: eat, drink, pull and sprinkle
Cat: meow (cat inherits animal function)
Dog: Barking (dogs inherit animal functions)
The following figure shows the code format of the subclass inheriting the parent class, that is, write the name of the parent class in parentheses after the name of the subclass of class
Then the problem comes again
- Can I inherit multiple classes?
Python classes can inherit multiple classes, while Java and C # can only inherit one class
- If you inherit multiple classes, each class has the same function, which one will be used?
If a Python class inherits multiple classes, there are two ways to find methods: depth first and breadth first
- When the class is a classic class, in the case of multiple inheritance, it will be searched according to the depth first method
- When the class is a new class, in the case of multiple inheritance, it will be searched according to the breadth first method
The classic class and the new class can be seen from the literal point of view. The new class must contain many functions, and it is also the recommended writing method. If the writing method is distinguished, if the current class or parent class inherits the object class, then the class is a new class, otherwise it is a classic class.
Classic class multi inheritance
class D: def bar(self): print 'D.bar' class C(D): def bar(self): print 'C.bar' class B(D): def bar(self): print 'B.bar' class A(B, C): def bar(self): print 'A.bar' a = A() # When executing bar method # First, search in class A. if it is not found in class A, continue to search in class B. if it is not found in class B, continue to search in class D. if it is not found in class D, continue to search in class C. if it is still not found, an error will be reported # Therefore, the search order is: a -- > B -- > D -- > C # In the above search method, once found, the search process will be interrupted immediately and the search will not continue a.bar()
New class multi inheritance
class D(object): def bar(self): print 'D.bar' class C(D): def bar(self): print 'C.bar' class B(D): def bar(self): print 'B.bar' class A(B, C): def bar(self): print 'A.bar' a = A() # When executing the bar method # First, search in class A. if it is not found in class A, continue to search in class B. if it is not found in class B, continue to search in class C. if it is not found in class C, continue to search in class D. if it is still not found, an error will be reported # Therefore, the search order is: a -- > B -- > C -- > D # In the above search method, once found, the search process will be interrupted immediately and the search will not continue a.bar()
Polymorphism refers to the use of instances without considering the type of instances. Regardless of the ever-changing objects, users can call them through a unified interface. The advantage of this is to increase the flexibility and scalability of the program.
For example, Python's sequence types have many forms: string, list and tuple, but we can use the same method to calculate the length of the sequence without considering the three types, which is an embodiment of polymorphism.
# STR, list and tuple are all sequence types s = str('hello') l = list([1, 2, 3]) t = tuple((4, 5, 6)) # We can use s,l,t without considering the three types s.__len__() l.__len__() t.__len__() len(s) len(l) len(t)
Pyhon does not support polymorphic writing in strongly typed languages such as Java and C# but it is native polymorphic, and its Python advocates "duck type". If it looks like a duck, sounds like a duck and walks like a duck, it is a 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 create a new object that looks and behaves like it, but has nothing to do with it. The latter is usually used to save the loose coupling of program components.
Python implements polymorphism in Java or C #
class F1: pass class S1(F1): def show(self): print 'S1.show' class S2(F1): def show(self): print 'S2.show' # Because in Java or C#When you define a parameter type in a function, you must # In order to enable Func function to execute both the show method of S1 object and the show method of S2 object, a parent class of S1 and S2 classes is defined # The parameters actually passed in are S1 object and S2 object def Func(F1 obj): """Func Function needs to receive a F1 Type or F1 Type of subclass""" print obj.show() s1_obj = S1() Func(s1_obj) # Pass in S1 class object S1 in Func function_ Obj, execute the show method of S1, and the result is S1 show s2_obj = S2() Func(s2_obj) # Pass in the object Ss of the Ss class in the Func function_ Obj, execute the show method of Ss, result: S2 show
How to choose between functional programming and object-oriented programming? Under what circumstances?
A: for C# and Java programmers, this problem does not exist, because these two languages only support object-oriented programming (not functional programming). For languages such as Python and PHP, two programming methods are supported at the same time, and the operations that can be completed by functional programming can be realized by object-oriented programming; However, for the operations that can be completed by object-oriented, functional programming cannot (functional programming cannot realize the object-oriented encapsulation function).
Therefore, in general, in Python development, object-oriented and functional are usually mixed