Python-Object-Oriented Programming and python Object-Oriented Programming
Object-Oriented Programming is simply based onClassAndObjectAll the code is implemented by class and object programming is object-oriented programming!
Three main features of object-oriented architecture:Encapsulation, inheritance, and Polymorphism
First create a class
# Create a School class using class. The class has a student method class School: def student (self): passa1 = School ()
I. Encapsulation
1. encapsulation: encapsulate some content in one place and call it when necessary.
Class School: def _ init _ (self, name, age): # constructor. the object to be created is self. name = name self. age = age # create object a1, a2a1 = School ("zhangsan", 18) a2 = School ("lisi", 18)
The code above implements the encapsulation function. encapsulating their names and age into the name and age attributes of self is equivalent to being encapsulated into the a1 and a2 objects.
The function defined in the class is called a method, and the function with _ init _ is called a constructor. It is automatically executed when the a1 and a2 objects are created.
2. Call: There are two methods for calling: directly calling through objects and indirectly calling through self.
Direct call through objects
Class School: def _ init _ (self, name, age): self. name = name self. age = age def student (self): print ("name: % s, age: % s" % (self. name, self. age) # create the a1, a2a1 = School ("zhangsan", 18) a2 = School ("lisi", 18) # execution result: # name: zhangsan, age: 18 # name: lisi, age: 18
Indirect call through self
Class School: def _ init _ (self, name, age): self. name = name self. age = age def student (self): print ("name: % s, age: % s" % (self. name, self. age) # when creating an object a1, a2a1 = School ("zhangsan", 18) a2 = School ("lisi", 18) # When executing a method in the class, indirectly calling encapsulated content a1.student () a2.student () # execution result: # name: zhangsan, age: 18 # name: lisi, age: 18
Ii. Inheritance
1. Inheritance: The derived class (subclass) can inherit the methods of the base class (parent class). We can extract the methods common to multiple classes to the parent class, in this way, the subclass only needs to inherit the parent class and does not need to implement each method one by one.
Write another class in the brackets behind the class name, indicating that the class is inherited.
# Use class to create a School class School: def _ init _ (self, name, age): self. name = name self. age = age def student (self): print ("name: % s, age: % s" % (self. name, self. age) def classroom (self): print ("% s going to classroom" % self. name) class SchoolA (School): # SchoolA inherits School def _ init _ (self, name): self. name = nameclass SchoolB (SchoolA): # SchoolB inherits SchoolA def _ init _ (self, name): self. name = name # create object a1a1 = SchoolA ("zhangsan") a1.classroom () # create object a2a2 = SchoolB ("lisi") a2.classroom () # execution result: # zhangsan going to the classroom # lisi going to the classroom
In the above code, we can see that neither SchoolA nor SchoolB has the classroom method, but because SchoolB inherits SchoolA and SchoolA inherits School, they can
Call the classroom method in School.
2. Multi-Inheritance
In python, a class can inherit multiple classes. When inheriting multiple classes, it can find functions in the class in two ways.
Depth first: When a class is a classic class, if there are multiple inheritance classes, it will be searched by depth first.
Breadth First: When a class is a new class, if there are multiple inheritance classes, it will be searched in the breadth-first mode.
(In python3.x) both have the breadth-first priority by default, but you can still understand the differences between the two,New category: The current class or base class inherits the objiect class and is called the new class. No, it is a classic class.
In python2.7
# Python2.7 classic class A (): def name (self): print ("AAAAAA") class B (A): passclass C (A): def name (self ): print ("CCCCCC") class D (B, C): passa1 = D () a1.name () # output: AAAAAA # search order: # first, search in your own class D, if no, continue to search for class B. If no, continue to search for Class A. If no, continue to search for Class C. If not, report an error # depth first: d-B-A-C
# Python2.7 New class A (object): def name (self): print ("AAAAAA") class B (A): passclass C (A): def name (self): print ("CCCCCC") class D (B, C): passa1 = D () a1.name () # output: CCCCCC # search order: # first, go to your own class D, if no, continue to search in Class B. If no, continue to search in Class C. If no, continue to search in Class A. If not, report an error # breadth first: d-B-C-A
In the above two examples, we can see that the output results of classic and new types are different because their search order is different.
In python2.7, the prerequisite for breadth-first is that D inherits BC and BC inherits A at the same time. Only when this condition is met will the new class follow breadth-first. Otherwise, no, for example:
Class A (object): def name (self): print ("AAAAAA") class B (A): passclass C: def name (self): print ("cccccccc ") class D (B, C): passa1 = D () a1.name () # output: AAAAAA
If C does not inherit A, then even if you are A new class, it will find it in the depth-first order.
After python3.X, there is no such difference, and its search order isBreadth First
Iii. Polymorphism
Python does not support polymorphism, nor does it use polymorphism. python is a polymorphism language that advocates duck type.
Iv. Members in the class
Class Members: fields, methods, and attributes
1. Fields
Fields: common fields and static Fields
Class School: headmaster = "" def _ init _ (self, name, age): self. name = name self. age = age def student (self): print ("name: % s, age: % s" % (self. name, self. age) # create the object a1a1 = School ("zhangsan", 18) print (a1.name) # access the common field print (School. headmaster) # access static fields # execution result: # zhangsan # Wang Wu
In the code above, the __init _ function is a common field, and the headmaster is a static field.
Common field: belongs to the object and is accessed by the object. Each object must be saved in the memory.
Static Field: it belongs to the class and is directly accessed by the class. Only one copy is saved in the memory.
2. Method
Methods: common methods, static methods, and class methods
Class School: headmaster = "" def _ init _ (self, name, age): self. name = name self. age = age def student (self): # A normal method must have at least one self print ("normal method") @ staticmethod # Any parameter of the static method def classroom (): print ("static method") @ classmethod def dormitory (cls): # The class method can only be one cls print ("class method", cls) # create an object a1a1 = School ("zhangsan", 18) a1.student () School. classroom () # access the static method School. dormitory () # statement class method ''' execution result: normal method static method class method <class '_ main __. school> '''
Common method: first create an object and call this method with the object
Static Method: You can call it directly using a class and have any parameters. (Static methods allow classes to be called directly, eliminating the need to create objects using common methods)
Class Method: called directly by class. Only one cls parameter is allowed.
The preceding figure shows that when the execution class method is executed, the input parameter is equal to <class '_ main __. school '>, is a class, that is, it will pass the current class as a parameter during execution.
3. Attributes
Attribute definition: decorator definition and static field Definition
(1) decorator Definition
Class School: headmaster = "" def _ init _ (self, name, age): self. name = name self. age = age def student (self): # method print ("method") @ property def classroom (self): # attribute, plus @ property modifier, only one self parameter print ("attribute") # create the object a1a1 = School ("zhangsan", 18) a1.student () # Call method a1.classroom # Call attribute # execution result: # method # attributes
As you can see in the code above, adding the @ property modifier to the method is called the property. The difference between the property and the method is that when callingNo parentheses
In the new class, in addition to @ property, there are two other decorators
Class School (object): def _ init _ (self, name, age): self. name = name self. age = age @ property def classroom (self): # attribute, coupled with the @ property modifier, only one self parameter print (self. name, self. age) @ classroom. setter def classroom (self, age): self. age = age # change age to the input parameter print ("modify", self. name, self. age) @ classroom. deleter def classroom (self): del self. age # Delete age print ("delete", self. name, self. age) # create an object a1a1 = School ("Zhang San", 18) a1.classroom #1. the @ property method a1.classroom = 20 #2 is automatically called after execution. @ classroom is automatically called after execution. setter method, and pass 20 to age parameter del a1.classroom #3. @ classroom is automatically called after execution. execution result of the 'Er method ''': Zhang San 18 modifies Zhang San 20 and reports an error when executing 3, because age is already in @ classroom. the method below deleter is deleted, so self is output. age error '''
(2) static field Definition
Class School (object): def _ init _ (self, name, age): self. name = name self. age = age def classroom (self): print (self. name, self. age) def classroom_update (self, age): self. age = age # change age to the input parameter print ("modify", self. name, self. age) def classroom_del (self): del self. age # Delete age print ("delete", self. name, self. age) obj = property (classroom, classroom_update, classroom_del) # define attributes using static fields # create an object a1a1 = School ("James", 18) a1.obj #1. the classroom method a1.obj = 20 #2 is automatically called after execution. after execution, the classroom_update method is automatically called, and 20 is passed to the age parameter del a1.obj #3. the classroom_delr method is automatically called after execution.
4. Public and Private Members
Each member of a class has two forms: public and private.
Public: All can be accessedPrivate: Accessible only within the class
Examples
Field
Class School (object): deg = "dog" # public static field _ cat = "cat" # Private Static Field def _ init _ (self, name, age ): self. name = name # public common field self. _ age = age # private common field def dormitory (self): print (self. _ age) def cat (self): print (School. _ cat) # create an object a1a1 = School ("Zhang San", 18) # access the common field print (a1.name) # output: Zhang San print (a1.age) # error: no age is displayed, because age is a private field, you can only access a1.dormitory () indirectly. # You can only access private fields through the class. # access static field print (School. deg) # output: dog print (School. _ cat) # error a1.cat () # output: the cat can indirectly ask private static fields through the internal cat method.
Method
Class School (object): def _ init _ (self, name, age): self. name = name self. _ age = age def cat (self): # public method print ("cat") def _ dog (self): # private method print ("dog ") def doo (self): # Internal access private method a1. _ dog () # create object a1a1 = School ("Zhang San", 18) a1.cat () # output: cata1.dog () # error a1.doo () # output: dog indirectly asks the private method _ dog through the doo Method
Other members in the class are similar
5. Special members in the class
(1)_ Doc __
Class School (object): "class description" def _ init _ (self, name, age): self. name = name self. _ age = ageprint (School. _ doc _) # output: Class description
(2)_ Init __
As mentioned above, when creating an object, it is automatically executed.
(3)_ Del __
Automatically triggered when an object is released in the memory
(4)_ Call __
The _ call _ method in the class is automatically executed when the created object is followed by parentheses.
Class School (object): def _ call _ (self, * args, ** kwargs): print ("trigger _ call _ method") a1 = School () a1 () # output: trigger _ call _ method School () # output: trigger _ call _ Method
(5)_ Dict __
Obtains all the members of a class or object.
Class School (object): "class description" cat = "cat" def _ init _ (self, name, age): self. name = name self. _ age = age def dog (self): print ("dog") print (School. _ dict _) # obtain the a1 = School ("Zhang San", 18) print (a1. _ dict _) of the class # obtain the '''member in the object and output it: {'cat': 'cat', '_ init _': <function School. _ init _ at 0x000000000226C950>, '_ dict _': <attribute '_ dict _' of 'school 'objects>, '_ weakref _': <attribute '_ weakref _' of 'school 'objects>,' _ module _ ':' _ main __', 'Dog ': <function School. dog at 0x000000000226CAE8>, '_ doc _': 'class description information'} {'name': 'zhang san', '_ School _ age ': 18 }'''
(6)_ Str __
No _ str __
Class School (object): def _ init _ (self, name, age): self. name = name self. _ age = agea1 = School ("Zhang San", 18) print (a1) # output: <__main __. school object at 0x000000000222B278>
_ Str __
Class School (object): def _ init _ (self, name, age): self. name = name self. _ age = age def _ str _ (self): return ("returned value when the print Object") a1 = School ("Zhang San", 18) print (a1) # output: The returned value when the print Object is returned.
Other special members are not listed one by one, because they are not used in most cases.
See http://www.cnblogs.com/wupeiqi/p/4766801.html for details