[Path] [python's not understood before 1] object-oriented (initial, grammar)

Read so many videos, or Alex's easy to understand, moving from https://book.apeland.cn/details/155/

Object-oriented process-oriented VS

1, the programming paradigm

Programming is the code a programmer with a specific grammatical structure + algorithm + data consisting of process to tell the computer how to perform a task, a program is a set of instructions that programmers in order to get a written task results, the saying goes, all roads lead to Rome, a way to achieve a task many different ways, the characteristics of these different ways of programming are summarized way out of the programming categories, namely programming paradigm. Represent different ideas to solve problems of all kinds of jobs to take on a different nature programming paradigm, most languages ​​only support a programming paradigm, of course, some languages ​​can simultaneously support multiple programming paradigms. The two most important programming paradigms are process-oriented programming and object-oriented programming.

1.1 Process-oriented programming (Procedural Programming)

Procedural programming uses a list of instructions to tell the computer what to do step-by-step.

Process-oriented programming relies - you guessed - Procedures, a calculation procedure includes a set of steps to be performed, the process is also known for the top -down languages, the program is executed from top to bottom, step by step, step by step from top to bottom, from beginning to end solution to the problem. The basic idea is to design a program to begin to address a big problem, and then break down a large problem into many small problems or sub-process, process re-execution of these sub-processes of decomposition and then continue until the small problems are simple enough to be in a within the range of small steps to resolve.

For example, a typical process-oriented, there is a demand for website log analysis, generate e-mail reports, the entire process divided into the following steps:

1. Go to each server to collect logs, because more than one server, common external service

2. Log on various dimensions of analysis, such as pv, uv, area of ​​origin, access to equipment,

3. generate reports, send e-mail

code show as below

# 1 consolidated log 
DEF collect_logs ():
  Print ( " log ON Server A, the access.log GET " )
  Print ( " log ON Server B, the access.log GET " )
  Print ( " log Server C ON, the access.log GET " )
  Print ( " as Combine logs in to One File " )
 
# 2 log analysis DEF log_analyze (log_file):   Print ( " pv, uv analysis .... " )   Print ( " user source analysis .... " )   Print ( " device originated access analysis .... " )   Print ( " Time on Page analysis .... " )   Print ( " entry page analysis .... " )

# 3 Report Generation and Delivery DEF send_report (Report_data) :   Print ( " Connect Email Server ... " )   Print ( " the send Email .... " )

DEF main ():   collect_logs ()   log_analyze ( ' my_db ' )   send_report ()

IF __name__ ==' __Main__ ' :   main ()

 

The problem with this is obvious, that if you want to modify the program, there are various parts of the dependent you also need to change, for example, if you set the beginning of the program on the part of a variable you modify a value of 1 However, if other sub-processes depend on the value of a variable to run properly, that if you change this variable, then this subroutine you should also be amended, if there is another other sub-routines rely on this process, it will happen a series of influence, as the program is growing, difficult to maintain this programming approach will be increasingly high.

So we generally think that if you just write a simple script to do some one-time task, with a process-oriented approach is excellent, but if you want to handle the task is complex and requires constant iteration and maintenance, that was the most convenient object-oriented.

1.2 Object-oriented programming ( Object-Oriented Programming )

OOP programming is the use of "class" and "object" to create a variety of models to achieve a description of the real world, the use of object-oriented programming For one, because it can make the maintenance and expansion of the program easier, and greatly improve program development efficiency, in addition, based on object-oriented programming can make it easier for people to understand your code logic, enabling the team to develop to become more calm.

Object-oriented features include several core

  Class class

A class object that is a class have the same attributes abstract, blueprints, prototypes. These objects are defined in the class attributes included (variables (data)), a common method of

   Object Object

Instantiate an object that is an instance of the class, a class must be called in the program only after instantiated, a class can instantiate multiple objects, each also can have different attributes, just like humans refers to all people, everyone refers to a specific target, before people have in common, there are also different

  Encapsulation package

In the class assignment of data internal to external calls transparent to the user, which makes the class into a container or capsule, which contains the data and methods of the class

  Inheritance succession

A class can derive subclasses, attributes defined in the parent class, method automatically inherited by subclasses

  Polymorphism Polymorphism

 Polymorphism is the important feature of object-oriented, simple point that: "an interface, a variety of implementation," refers to a group derived class different subclasses, and each subclass inherits the same name at the same time the method of the method of the parent class to do a different realization, this is the show of the same thing a variety of forms.


The program is actually a concrete world abstracting process, polymorphism is a reflection of abstraction, the common number of specific things abstracted, then, dialogue with different specific things through this abstract thing.

They sent the same message to different classes of objects will behave differently. For example, your boss so that all employees start work at nine o'clock, he was just nine o'clock, said: "start work" can be, without the need for sales staff said: "start sales," said technician : "start technical work" because "employee" is an abstract thing, as long as the employee can start work, he knows it on the line. For each employee, of course, they will carry out their duties, do their work.

Polymorphism allows the object as an object subclass using the parent class, a reference to its parent type of pointing object subtype, the method calls the sub-types. The entire code is compiled and before the called method has already decided, and the reference points to an object can be dynamically bind during operation

1.3 vs object-oriented process-oriented summary

The core process-oriented programming is the process (assembly line thinking), step problem-solving process that is process-oriented design is like an assembly line better than well-designed, well thought when handling anything.

Advantages are: greatly reduces the complexity of the writing process, just follow the steps to follow, stacked code.

The disadvantages are: a pipeline or process is used to solve a problem, the code indeed affect the whole body.

Object-oriented programming is the core of the object (God thinking), to understand why the object must regard themselves as God, all things are all objects exist in the eyes of the world God does not exist can be created. Object-oriented programming such as good design Journey to the West, such as the problem to be solved is to pass through the book lands east Datang, such as the need to address this issue thought four people: monk, Shahe Shang, Pig, Monkey King, everyone have their own characteristics and skills (this is the concept of the object, characteristics and skills respectively corresponding to the object properties and methods), but this is not fun, so the Tathagata has also arranged for a group of demons, in order to prevent mentoring four were engaged during the journey dead, has also arranged for a group of gods escort, these are objects. Then learn start, mentoring four gods and demons fight with one another until finally made Scriptures. Tathagata would not pick up tube in accordance with what mentoring four processes.

Object-oriented programming

Advantages are: to solve the scalability of the program. Modification of a single object, are immediately reflected throughout the system, such as characteristics and skills to modify the parameters of a character in the game is very easy.

Disadvantages: poor control, can not be pipelined design can be very accurate prediction problem handling process and the results of the process-oriented programming, object-oriented programming once you start to solve the problems caused by the interaction between objects , even God can not predict Final Results. So we often see people modify a parameter of a game is likely to lead to negative Pa skills appear knife hacked to death three people, this game is out of balance.

Scenario: constantly changing demands of software, changes in the general demand is concentrated in a good place for the user layer, Internet applications, enterprise software, games, etc. are object-oriented programming to show their talents.

2. Definition of the class

class Dog: # class name first letter capitalized, hump body 
  d_type = " Pekingese "  # public property, also known as class variables 
  DEF say_hi (self): # class methods, must take a self argument, on behalf of itself instance, specific first do not explain 
    Print ( " the Hello, the I AM a dog, My of the type iS " , self.d_type) # want to call class properties should add self., reason to not watch

d = dog () # generate a dog examples of D2 = dog () # create an instance of a dog d.say_hi () # method calls this class dog d2.say_hi () Print (d.d_type) # call public property class dog

The above code is the definition of a good Dog class, Mr. became the equivalent of a template, the next generation of the two examples d, d2, equivalent to two flesh and blood of dogs were created.

d_type is a class variable, all instances of common attributes Dog class, it exists in memory Dog class itself. You can view d1.d_type, d2.d_type memory address, pointing to the same place

In addition to common attributes, there is no private it? For example, each dog's name, age, the owner is not the same. Possible, on the line as follows:

class Dog: # class name first letter capitalized, hump body 
  d_type = " Pekingese "  # public property, also known as class variables 
  DEF  __init__ (Self, name, Age, Master): # initialization function, as long as one example of the will performed automatically 
    Print ( ' initializes the instance .... ' , name) 
    the self.name = name # the self.name is its own instance variables 
    self.age = Age 
    self.master = Master
  
  DEF say_hi (Self): # methods of the class , you must take a self parameter representative example of itself, specifically to not construed     Print ( " Hello, the I AM a Dog, My type IS " , self.d_type)# Want to call class attributes should add self., No reason to Table
D = Dog ( " hairy " , 2, " Alex " ) # generates an instance of dog D2 = Dog ( " two eggs " , 3, " Jack " ) # create an instance of a dog d.say_hi () # call the method of this class dog d2.say_hi () Print (d2.name, d2.age, d2.master) # call instance variables

 

Perform output

Examples of this initialization .... plush 
initialize this example two egg .... 
Hello, the I AM A Dog, My type IS Beijing bus 
Hello, the I AM A Dog, My type IS Beijing buses 
two eggs 3 Jack

We did not call the init (Self, ....), But it is performed automatically, as it is called initialization function, that is instantiated, used to initialize some data, such as initialize your instance name, age and other attributes friends.

These written in the init (Self, xxxx) in the name, age, master variables, what difference does it with d_type?

Difference is, d_type Dog class is the presence of his memory, self.name, self.age, self.master exist for each instance of your memory

3.self in the end is what the hell?

Self want to understand what it meant, we first thoroughly understand instantiation process, see the figure;

1. step 1, d = Dog ( "hairy", 2, "Alex") would apply for a memory space, variable names point d

STEP 2 2.,  the init (XXXX) This method requires the received initialization parameter survive, to save memory space in the d

3. step 3, passed to the initialization method in the name, age, master want to bind to the space d, how you keep it? D have the memory space in the spread of this method, the self address is used to receive a d. d = Dog ( "hairy", 2, "Alex") corresponds Dog (d, "plush", 2, "Alex"), it is equivalent to that self.name = name d.name = name. We are instances when there is no manual transfer d to the Dog class, just write d = Dog ( "hairy", 2, "Alex"), the Python interpreter to help you to automatically done this thing.

This, we finally understand that the original self is to represent the instance itself. When you instantiate the python will automatically pass in this instance itself through self parameter.

Well you say, pretending to understand, but the following piece of code you do not understand, why say_hi (self), to write a self it? 

def say_hi(self): # 类的方法,必须带一个self参数,代表实例本身
  print("hello , I am a dog,my type is ",self.d_type,self.name) # 想调用类里的属性,都要加上self.

那是因为,你自己也看到了, 这个类的方法其实就是一堆函数对吧。函数被一个实例调用时,它怎么知道是谁在调用它呢? 函数内部要用到一些实例的属性的时候去哪里取呢? 比如在say_hi函数里怎么取到d.name,d.age?只能你先传递给它。 所以这就是为何类下的每个方法第一个参数都要是self,因为是为了接收实例这个对象本身。

*注意:self在实例化时自动将对象/实例本身传给init的第一个参数,你也可以给他起个别的名字,但是正常人都不会这么做,因为你瞎改别人就不认识。

4.属性引用

  4.1类的公共属性引用(类名.属性)

class Dog: # 类名首字母要大写,驼峰体
  d_type = "京巴" # 公共属性,又称类变量
  def say_hi(self):
    print("hello , I am a dog,my type is ",self.d_type)
    print(Dog.d_type) # 查看Dog的d_type属性
    print(Dog.say_hi) # 引用Dog的say_hi方法,注意只是引用,不是调用

  4.2实例属性引用(实例名.属性)

d2 = Dog("二蛋",3,"Jack") # 生成一个狗的实例
d2.say_hi() # 调用狗这个类的方法
print(d2.name, d2.age, d2.master) # 调用实例的属性
print(d2.d_type) # 注意通过实例也可以调用类的公共属性

练习一

设计一个类Person,生成若干实例,在终端输出如下信息

小明,10岁,男,上山去砍柴

小明,10岁,男,开车去东北

小明,10岁,男,最爱大保健

老李,90岁,男,上山去砍柴

老李,90岁,男,开车去东北

老李,90岁,男,最爱大保健

老张…

Guess you like

Origin www.cnblogs.com/watalo/p/12305699.html