Python study notes 8--object-oriented programming

1. Object-Oriented Programming

Object-oriented - Object Oriented Programming, referred to as oop, is a programming idea. Before talking about object-oriented, let's talk about what a programming paradigm is, and how do you program in a programming paradigm to implement a function. For example, if you want to cook, you can use an induction cooker or a gas cooker. Different programming paradigms essentially represent different approaches to problem solving for various types of tasks. The two most important programming paradigms are procedural programming and object-oriented programming.

When it comes to object-oriented, we have to mention another programming idea, process-oriented; what is process-oriented? , what to do first, what to do later, until the end. This kind of thinking is easy to understand. In fact, this is also the way a person does things. Our previous programming ideas also use this kind of thinking. This kind of programming idea, as long as one step is changed in the front, then the latter will also change, and it is more troublesome to maintain later. This kind of programming idea can be used when writing some simple small programs and scripts that are executed only once. As for object-oriented, the idea of ​​object-oriented is to divide a project or a thing into smaller projects, or into smaller parts, each part is responsible for what function, and finally these parts are combined to become a overall. This kind of thinking is more suitable for the division of labor and cooperation among many people. It is like a large organization, divided into various departments, each department is responsible for a certain function, and each department can give full play to its own characteristics, as long as certain preconditions are met.

For example: For example, if a large organization is to do a certain project, it should be analyzed in this way from the perspective of process-oriented thinking, first, then, and finally. How the first should be done, how the second should be done, etc. When each step is completed, the project is complete. Object-oriented thinking should be like this, this project is composed of several parts, we will do a good job of division of labor, set up a department to do the function of one part, and another department to do another part. Each department does not need to understand the affairs of other departments, as long as it completes its own part of the work, it will be OK.

2. Object-Oriented Features

class: class

A class, compared to the real world, is a category, a model.

A class is an abstraction, blueprint, or prototype for a class of objects with the same properties.

The attributes (variables(data)) and common methods of these objects are defined in the class.

object: object

Objects refer to the specific things created by the model.

An object is an instantiated instance of a class. A class must be instantiated before it can be called in a program. A class can instantiate multiple objects, and each object can have different properties. People, each person refers to a specific object, and people have similarities and differences before.

Instantiate:

Initialize a class and create an object. The process of turning a class into a concrete object is called instantiation.

Package:

The implementation details of some functions are not exposed to the outside world, and the assignment of data and internal calls in the class are transparent to external users, which turns the class into a capsule or container, which contains the data and methods of the class.

For example, if you create a person, you encapsulate the heart, liver, spleen, lungs, and kidneys in his body, so that no one else can see it, so you directly look for this person.

inherit:

A class can derive subclasses, and the properties and methods defined in this superclass are automatically inherited by subclasses. Say you inherited your father's surname.

Multiple inheritance in python3 is breadth first, multiple inheritance of classic classes in python2 is depth first, and multiple inheritance of new-style classes is breadth first.

Inheritance is for code reuse

Polymorphism:

Sending the same message to objects of different classes will behave differently. For example, if your boss asks all employees to start work at nine o'clock, he only needs to say "start work" at nine o'clock, instead of saying "start sales work" to the salesperson, say to the technical staff : "Start technical work", because "employee" is an abstract thing, as long as it is an employee, he can start work, he knows it. As for each employee, of course, they will perform their own duties and do their own work.

Polymorphism is an embodiment of abstraction, which abstracts the common points of a series of concrete things, and then communicates with different concrete things through this abstract thing.

One interface, many implementations.

The benefits of object orientation

For beginners of programming languages, OOP is not an easy-to-understand programming method. Although everyone knows that the three major characteristics of OOP are inheritance, encapsulation and polymorphism according to what the teacher said, and everyone also knows how to define classes , methods and other common object-oriented syntax, but when it comes to actually writing programs, many people still like to use functional programming to write code, especially beginners, it is easy to fall into a dilemma: "I know object-oriented, I will also Write classes, but I still haven't found any benefits to our program development efficiency or other aspects after using object-oriented, because I can reduce repetitive code and make the program scalable by using functional programming. Why? Object-oriented?" For this, I personally think the reason should be because you don't fully understand the benefits that object-oriented can bring.

Regardless of the form of programming, we must clearly remember the following principles:

Writing duplicate code is very bad low-level behavior

The code you write needs to change frequently

A big difference between developing a regular program and writing a small script that is run once and thrown away is that your code always needs to be changed continuously, either by modifying bugs or adding new functions, etc., so in order to facilitate the modification of the program in the future, and To expand, the code you write must follow the principles of easy readability and easy modification (professional data is called good readability and easy expansion).

If you copy and paste the same piece of code to multiple places in the program to call this function in various places in the program, when you modify this function in the future, you need to change multiple places in the program. , this way of writing programs is problematic, because if you accidentally miss a place and leave it unchanged, it may cause problems with the operation of the entire program. Therefore, we know that we must try to avoid writing repetitive code during development, otherwise it is equivalent to digging holes for ourselves.

Fortunately, the appearance of functions can help us easily solve the problem of repeated code. For functions that need to be called repeatedly, we only need to write it as a function, and then call the function name directly in various places in the program, and when When you need to modify this function, you only need to change the function code, and then the entire program is updated.

In fact, the main function of OOP programming is to make your code modification and expansion easier, so Xiaobai has to ask, since the functions can meet this requirement, what about OOP dry wool? Hehe, saying this is like, in ancient times, people used knives to kill people. Later, guns came out. Its main function is the same as knives. It also kills people. Then Xiaobai asked, since knives can kill people, then guns Dry wool, haha, obviously because guns kill people better, faster and easier. The main difference between functional programming and OOP is that OOP makes programs easier to extend and change.

4. Class

Some concepts:

Attribute: An attribute is a variable in a class. There are class variables and instance variables. Class variables exist when the class is defined, and instance variables are variables that are generated when the class is instantiated. This can be understood as a person is a class, and his name, age, and gender are its attributes.

Method: Method is the function of the class, that is, the function defined in the class, which implements a certain function, such as the function of people sleeping.

Constructor: What is a constructor, that is, some initialization operations that a class does when it is instantiated. For example, when you build a car, it must have a color, a model, and so on.

Destructor: The destructor is the operation that the instance does when it is destroyed.

Define class:

The class keyword is used to define a class. Generally, the first letter of the class name should be capitalized when we develop it. There are classic classes and new-style classes in python. There is no difference between them in python3. In python2, classic classes are depth-first in multiple inheritance, and new-style classes are breadth-first. Unity in python3 is breadth first, which will be mentioned later when we talk about inheritance.

class Car(): #model, template
	def __del__(self):
		#Destructor, the execution of this instance is destroyed.
		print('over..')

	def my_self(self):
		print(
			'I am a car my color is [%s], I have [%s] windows'%(self.color, self.window)
		)
		self.price = 10002
	def run(self):
		print(self.color)
		print(self.window)
		print(self.price)
		print('The car is running...')

	def __init__(self,color,window):
		#
		#Constructor, which is executed when the class is initialized
		#If your class needs to pass in some parameters when instantiating, then you have to write the parameters in the __init__ function
		self.color = color #Binding properties
		self.window = window
		print('Executed me..')

#Make the model into an actual car, this process is called instantiation.
bus = Car('yellow','3 open the door') #Instantiation
bus2 = Car('black', '4 doors') #Instantiation
bus3 = Car('pink', '2 open the door') #Instantiation
bus.my_self()   #
bus2.my_self()
bus3.my_self()

#Instance refers to what is specifically created, and what is processed through class instantiation is an instance
#Object, is the instance

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325023305&siteId=291194637