First, object-oriented programming
Object-oriented--object oriented programming, short for OOP, is a programming idea. Before we talk about object-oriented, let's talk about what is the programming paradigm, the programming paradigm, and the way you go about programming, to implement a function. For example, you have to cook, you can use an induction cooker, or you can use a gas stove. The different programming paradigms essentially represent the different problem-solving ideas taken for various types of tasks, and the two most important programming paradigms are process-oriented programming and object-oriented programming.
Referring to object-oriented, we have to mention another kind of programming idea, process-oriented, what is the process-oriented idea is to put a project, a thing in a certain order, from beginning to end, do what first, what to do, all the way down to the finish. This idea is better understood, in fact, it is also a person's way of doing things, our previous programming ideas are also using this idea. This kind of programming thought, as long as there is a step in front of the change, then the back will be changed, the latter is more trouble to maintain, such a programming idea, we write some simple small program, only execute once script can be used. Object oriented, object-oriented thinking is to divide a project, a thing into smaller projects, or into a smaller part, each part responsible for what aspects of the function, and finally by the combination of these parts become a whole. This kind of thought is more suitable for many people's Division of labor, like a large organ, divided into various departments, each department is responsible for a certain function, each department can give full play to their own characteristics, as long as a certain premise on the line.
For example: For example, just said a large organ, to do a certain project, from the process-oriented thinking, it should be this analysis, first how, then how, finally how. How the first should be done, how the second should be done, and so on. When each step is completed, the project is completed. And the object-oriented thought should be like this, the project is composed of several parts, we will do a division, set up a department to do a part of the function of another department to do another part. Departments can not understand other departments, as long as the completion of their own part of the matter is OK.
Second, object-oriented characteristics
Classes: Class
class, compared to the real world, is a kind, a model.
A class is an abstraction, a blueprint, a prototype for a class of objects that have the same properties.
The properties of these objects (variables (data)) and common methods are defined in the class.
Objects: Object
Object, that is, the concrete thing created by the model.
An object is an instantiated instance of a class, a class must be instantiated before it can be called in the program, a class can instantiate multiple objects, each object can also have different properties, like human refers to everyone, each person refers to the specific object, people and people before there is a common, but also different.
Instantiation:
Initializes a class, creating an object. The process of turning a class into a concrete object is called instantiation.
Packaging:
The implementation details of some functions are not exposed, the assignment of data in the class, the internal invocation is transparent to the external user, which makes the class become a capsule or container, in which the bread implies the data and methods of the class.
For example, create a person, you put his body inside of what heart spleen lungs and kidneys are sealed up, other people can not see, you directly find this person.
Inherited:
A class can derive a subclass, and the properties, methods defined in the parent class automatically inherit the quilt class. For example, you inherit your father's surname.
Multi-Inheritance in Python3 is the breadth first, and the multi-inheritance of classical class in Python2 is the depth first, and the multi-inheritance of the new class is in the breadth first.
Inheritance is for the reuse of code
Polymorphic:
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.
Polymorphism is a manifestation of abstraction that abstracts out the common denominator of a series of specific things and then, through this abstraction, dialogues with different specific things.
An interface, a variety of implementations.
Iii. Object-oriented benefits
For beginners of programming language, OOP is not a very easy to understand programming, although everyone according to the teacher know that the three main features of OOP is inheritance, encapsulation, polymorphism, and everyone knows how to define classes, methods and other object-oriented common syntax, but one to really write programs, Still a lot of people like to use functional programming to write code, especially beginners, it is easy to fall into a dilemma is "I know object-oriented, I will write classes, but I still do not find that after the use of object-oriented, to our program development efficiency or other aspects of what benefits, Because I can use functional programming to reduce duplication of code and do the program extensible, why also use object-oriented? "For this, I personally think the reason should be because you do not fully understand the benefits of object-oriented."
No matter what the form of programming, we have to clearly remember the following principles:
Writing duplicate code is a very bad low-level behavior.
The code you write needs to change frequently.
The development of a formal program with the kind of writing a run-time throw the small script a very big difference is that your code always need to constantly change, not to modify the bug is to add new features, etc., so in order to facilitate program modification and extension, you write code must follow easy-to-read, easy to change the principle (professional data called good readability, Easy to expand).
If you copy a piece of the same code, paste it into the program in a number of places to implement the application in various places, this function, then you can change this function later, you need to change the program in many places, this way of writing the program is problematic, because if you accidentally missed a place not changed, That could lead to problems with the entire program running. So we know that in development we must try to avoid writing duplicate code, otherwise it is equivalent to digging holes for ourselves.
Fortunately, the appearance of functions can help us to easily solve the problem of duplicate code, for the function that needs to be repeated calls, only need to write it into a function, and then call the function name directly in each place of the program, and when it is necessary to modify the function, just change the function code, and then the whole program is updated.
In fact, the main role of OOP programming is to make your code modification and extension of the more easily, then the small white to ask, since the function can achieve this demand, but also the OOP dry yarn use it? Hehe, saying this is like, ancient times, people fight to kill all with knives, later came out of the gun, its main function with the same knife, but also kill, and then small White asked, since the knife can kill, that also gun dry yarn, haha, obviously, because the gun can be better faster and easier to kill. The main difference between functional programming and OOP is that OOP can make programs easier to scale and change.
Iv. class
Some concepts:
Property: A property is a variable within a class, with a class variable and an instance variable, a class variable is a class at the time it is defined, and an instance variable is a variable that is generated when instantiated. This can be understood as the person is a class, his name, age, sex is its attributes.
Method: The method is the function of the class, which is defined in the class function, it implements a function, for example, people have sleep function.
Constructor: What is a constructor, which is the initialization of a class when it is instantiated, such as a person, when you build a car, it has to have color, model, and so on.
Destructors: Destructors are some of the operations that this instance does when it is destroyed.
To define a class:
Define class using class keyword, class name generally we develop the first letter to capitalize. There are classic classes and new classes in Python, and they are not different in Python3, in which the classic class is depth-first in multiple inheritance, and the new class is breadth-first. The unification in Python3 is the breadth first, and this later says in succession.
Class Car (): #模型, Template def __del__ (self): #析构函数, this instance is destroyed by the execution. Print (' over.. ') def my_self (self):p rint (' I am a car my color is '%s ', I have '%s ' Windows '% (Self.color,self.window)) Self.price = 10002def run (self):p rint (self.color) print (Self.window) print (self.price) print (' The car is running ... ') def __init__ (Self,color,window): # #构造函数, the class executes it at initialization # If your class is going to pass in some arguments when it is instantiated, you will have to write the arguments in the __init__ function Self.color = Color #绑定属性self. Window = Windowprint (' Execute me. ') #把模型做成实际的一个汽车, this process is called instantiation. Bus = car (' Yellow ', ' 3 Open door ') #实例化bus2 = car (' Black ', ' 4 Open door ') #实例化bus3 = car (' Pink ', ' 2 Open Door ') #实例化bus. My_self () #bus2. My_self () Bus3.my_self () #实例就是指具体造出来的东西, what is handled by class instantiation is an instance # object, which is an instance
Inherited:
Class F (object): "This is the parent class" def __init__ (self,name,sex): self.name = name self.sex = Sex def info (): #方法 print (' name is%s sex is%s '% (Self.name,self.sex)) class S (F): # Inherit F This class pass S1 = S (' Bull ', ' man ') #实例化子类 s1.info () #因为继承父类, so the method of the parent class he has That if there is a method in the parent class, there is a subclass inside, but the subclass wants to rewrite the parent class method, add the new function to write the following: Class Test (): Def __init__ (self,n AME): Self.name = Name class Test1 (test): Def __init__ (Self,name, Age): # test.__init__ (self,name) #修改父类的方法, this is the classic class inside the super (test1,self). __ini T__ (name) #和上面的效果一样, this is the wording of the new class Self.name = name Self.age = Age Test1 (' name ', ' age ') Multiple inheritance, the above is written in single inheritance, Python also supports multiple inheritance, multi-inheritance is to inherit multiple parents, in the Python3 multiple inheritance is the breadth first, in Python2 a little different, the classic class is depth first, the new class is breadth first. Class A:def Say (self): print (' a ') class B (a): # Pass def Say (self): print (' B ') class C (A): Pass # def say (self): # print (' C ') class D (C,B): Pass S=d () S.say ()
Polymorphic: Python does not directly support polymorphism, and it can be done in other ways to achieve polymorphism. The following example can be implemented an interface, a variety of implementations, for the following cry method, regardless of what you pass in the object, as long as there is a cry method, will call its cry method, no more to call the
Class Animal (Object): "Parent class" def __init__ (self,name): Self.name = Name class Dog (Animal): ' Dog class, there's a way to call ' Def cry (self): Print (' Dog [%s] Wang Bark '%self.name) class Cat (Animal): ' Cat class, method of Barking ' Def Cry (self): print (' Cat [%s] meow meow '%self.name ') def cry (obj): "' defines a function to invoke the cry method of the passed in instance ' Obj.cry () D1 = dog (' rhubarb ') #实例化狗 D2 = Dog (' small yellow ') #实例化狗 C1 = Cat (' small white ') #实例化猫 C2 = Cat (' Little black ') #实例化猫 cry (D1) #把对象d1传进来 Cry (d2) #把对象d2传进来 OBJS = [d1,d2,c 1,C2] #把上面实例化的对象都放到一个listInside for obj in Objs: #循环统一调用 cry (obj)
Private methods, private properties: What is private, private is only accessible within the class, cannot be accessed and invoked after instantiation, has private methods and private properties. Private to the variable name or function name before the "__" two underline, in fact, through the private to achieve encapsulation.
Class Dog (object): __type = ' dog ' #私有属性 def Cry (self): self.__test () #调用私有方法 print (' Private property%s '%self.__ Type) print (' Dog [%s] Wang Barking '%self.name) def __test (self): #私有方法 self.name = ' Test ' # d = d () d.cry () # Normal can call d.__type# error, because it is a private property, outside cannot access the d.__test () #报错, because it is a private method, outside the access
Static Methods and class methods:
Class Stu (object): country = ' China ' #类变量 def __init__ (self,name): self.name = name @staticmethod #静态方法, it has nothing to do with the class itself, it's equivalent to defining a method in the class. def say (): print (' xxx ') @classmethod #静态方法, unlike class methods, It can use a class variable and must pass a value that represents the class def hello (CLS): print (cls.country) def hi (self): #这个是实例方法 Print (self.name) t = Stu (' name ') Stu.hello () Stu.say () T.hi () T.say ( ) T.hello ()
Python Learning note 8--Object-oriented programming