Python notes basic article-day6

Source: Internet
Author: User

Process-oriented VS object-oriented

Programming paradigm
Programming is a programmer with a specific syntax + data structure + algorithm composed of code to tell the computer how to perform the task of the process, a program is a programmer in order to get a task result and a set of instructions, is so-called all roads to Rome, the way to achieve a task there are many different ways, The types of programming that are summed up by the characteristics of these different programming methods are the programming paradigm. Different programming paradigms essentially represent different solutions to various types of tasks, and most languages support only one programming paradigm, and of course some languages can support multiple programming paradigms at the same time. Two of the most important programming paradigms are process-oriented programming and object-oriented programming.

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 dependencies-you guessed-procedures, a procedure contains a set of steps to be computed, and the process is called Top-down languages, which is the procedure from the top to the next step, step by step from top to bottom, to solve the problem from beginning to end. The basic design idea is that the program starts with solving a big problem, and then breaks down a big problem into many small problems or sub-processes, and the process continues to decompose until the small problem is simple enough to be solved within a small step.

The problem is also obvious, that is, if you want to modify the program, you have to modify the part of the dependent parts you also have to modify, for example, if the program at the beginning you set a variable value of 1, but if other sub-procedures rely on the value of 1 of the variable to run correctly, If you change this variable, then you have to modify this process, if there is another subroutine dependent on the sub-process, it will have a series of effects, as the program becomes larger, the maintenance of this method will be more difficult.
So we generally think that if you just write some simple scripts to do some one-off tasks, it's great to use a process-oriented approach, but if the task you're dealing with is complex and needs to be iterative and maintainable, it's the most convenient way to use object-oriented.


Object-Oriented Programming
OOP programming is the use of "class" and "object" to create a variety of models to achieve a real-world description, the use of object-oriented programming because it can make the maintenance and extension of the program easier, and can greatly improve the efficiency of program development, in addition, An object-oriented program can make it easier for people to understand your code logic and make team development easier.

Several core features of object-oriented are as follows

Class
A class is an abstraction, a blueprint, a prototype for a class of objects that have the same properties. The properties of these objects are defined in the class (variables (data)), common methods

Object objects
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, there are different

Encapsulation Package
The assignment of data in a class, internal invocation is transparent to external users, which makes the class A capsule or container in which the data and methods of the class are contained.

Inheritance inheritance
A class can derive subclasses, properties, methods defined in the parent class, automatic quilt class inheritance

Polymorphism Polymorphism
State is an important feature of object-oriented, simple point: "An interface, a variety of implementations," refers to a base class derived from a different subclass, and each subclass inherits the same method name, but also the method of the parent class to do a different implementation, this is the same thing shows a variety of forms.
Programming is actually a process of abstracting the concrete world, which is a manifestation of abstraction, abstracting the common denominator of a series of specific things, and then through this abstract thing, and dialogue with different concrete things.
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 allows the object of a subclass to be used as an object of the parent class, a reference to a parent type to an object of its subtype, and the method called is the method of that subtype. The code that references and invokes the method is already determined before it is compiled, and the object pointed to by the reference can be dynamically bound during run time


Introduction to Object-oriented programming (Object-oriented programming)


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 reason, I personally think that because you do not fully understand the benefits of object-oriented, I will write a primer on the object-oriented article, I hope to help you understand and use object-oriented programming.

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 invoke the function in various parts of the program, then you can change the function in the future, you need to change the program in a number of places, the way to write 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.


constructor function:
Class Role (object): #定义一个类, class is the syntax for defining classes, Role is the class name, and (object) is the style of the new class, which must be written, and then why
def __init__ (self,name,role,weapon,life_value=100,money=15000): #初始化函数, some of the properties to initialize when generating a role are filled in here
Self.name = name #__init__中的第一个参数self, and what does self mean here? Look at the following explanation
Self.role = Role
Self.weapon = Weapon
Self.life_value = Life_value
Self.money = Money

The above __init__ () is called the initialization method (or constructor method), when the class is called, this method (although it is a function form, but in the class is not called function, called method) will automatically execute, some initialization action, here write __init__ (self,name,role , weapon,life_value=100,money=15000) is to set these properties for a role when it is created.

To initialize a role, you need to call this class once:

R1 = Role (' Alex ', ' police ', ' AK47 ') #生成一个角色, the parameters are automatically passed to the __init__ (...) under role. Method
r2 = Role (' Jack ', ' terrorist ', ' B22 ') #生成一个角色
The above created role, did not give __init__ value, the program did not error, because, the class in the call its own __init__ (...) When you assign a value to the self parameter,


R1 = Role (' Alex ', ' police ', ' AK47 ') #此时self equivalent to R1, Role (R1, ' Alex ', ' police ', ' AK47 ')
r2 = role (' Jack ', ' terrorist ', ' B22 ') #此时self equivalent to R2, Role (R2, ' Jack ', ' terrorist ', ' B22 ')

When executing r1 = Role (' Alex ', ' police ', ' AK47 '), the Python interpreter actually did two things:
1. Open a space in memory pointing to the variable name R1
2. Call the role class and execute the __init__ (...) in it. method, equivalent to role.__init__ (R1, ' Alex ', ' police ', ' AK47 '), what is this for? To associate the 3 values of ' Alex ', ' police ', ' AK47 ' with the newly opened R1 in order to correlate the 3 values of ' Alex ', ' police ', ' AK47 ' with the newly opened R1 in order to put ' Alex ', ' police ', ' AK47 ' These 3 values are associated with the newly opened R1, as they can be directly r1.name, r1.weapon in order to invoke them. Therefore, in order to implement this association, when calling the __init__ method, it is necessary to R1 this variable is also passed in, otherwise __init__ do not know who to associate those 3 parameters.
So this __init__ (...) In the method, Self.name = name, Self.role = role, etc., means to store these values in the R1 memory space.

Summarize 2 points:
The above R1 = Role (' Alex ', ' police ', ' AK47 ') action, called the "instantiation" of a class, is to put a virtual abstract class, through this action, into a specific object, this object is called an instance
The class just defined represents the first basic object-oriented feature of encapsulation, which is to encapsulate content into a specific object using a construction method, and then indirectly get the encapsulated content through the object directly or self

Object-oriented features:
Packaging

The package is best understood. Encapsulation is one of the object-oriented features and is the main feature of object and class concepts.

Encapsulation, which is the encapsulation of objective things into abstract classes, and classes can put their own data and methods only trusted class or object operation, to the untrusted information hiding.

Inherited

One of the main functions of object-oriented programming (OOP) language is "inheritance". Inheritance refers to the ability to use all the functionality of an existing class and to extend these capabilities without rewriting the original class.

New classes created through inheritance are called "subclasses" or "derived classes."

The inherited class is called the base class, the parent class, or the superclass.

The process of inheritance is from the general to the special process.

To implement inheritance, it can be implemented through inheritance (inheritance) and combination (composition).

In some OOP languages, a subclass can inherit multiple base classes. However, in general, a subclass can have only one base class, and to implement multiple inheritance, it can be implemented by multilevel inheritance.

Inheritance concepts are implemented in three categories: implementation inheritance, interface inheritance, and visual inheritance.

Implementation of inheritance refers to the ability to use the properties and methods of the base class without additional coding;
Interface inheritance refers to the ability to use only the names of properties and methods, but subclasses must provide the implementation;
Visual inheritance refers to the ability of a subform (class) to look and implement code using the base form (class).
When considering using inheritance, it is important to note that the relationship between the two classes should be a "belongs" relationship. For example, the Employee is a person and the Manager is a person, so these two classes can inherit the People class. But the Leg class cannot inherit the person class, because the leg is not a human.

Abstract classes define only the generic properties and methods that will be created by the subclass.
OO development paradigm is roughly: dividing objects → abstract classes → organizing classes into hierarchical structures (inheritance and compositing) → Designing and implementing several stages with classes and instances.

Inheritance Example
Class Schoolmember (object):
Members = 0 #初始学校人数为0
def __init__ (self,name,age):
Self.name = Name
Self.age = Age

def tell (self):
Pass

def enroll (self):
' Register '
Schoolmember.members +=1
Print ("\033[32;1mnew member [%s] is enrolled,now there be [%s] members.\033[0m"% (self.name,schoolmember.members))

def __del__ (self):
"' Destruction method '
Print ("\033[31;1mmember [%s] is dead!\033[0m"%self.name)
Class Teacher (Schoolmember):
def __init__ (self,name,age,course,salary):
Super (Teacher,self) __init__ (name,age)
Self.course = Course
Self.salary = Salary
Self.enroll ()


def teaching (self):
"The method of lecturing"
Print ("Teacher [%s] is teaching [%s] for class [%s]"% (self.name,self.course, ' S12 '))

def tell (self):
"Self-Introduction method"
msg = ' Hi, my name is [%s], works for [%s] as a [%s] teacher! '% (self.name, ' Oldboy ', self.course)
Print (msg)

Class Student (Schoolmember):
def __init__ (self, name,age,grade,sid):
Super (Student,self) __init__ (name,age)
Self.grade = Grade
Self.sid = Sid
Self.enroll ()


def tell (self):
"Self-Introduction method"
msg = ' Hi, my name is [%s], I ' m studying [%s] in [%s]! '% (Self.name, Self.grade, ' Oldboy ')
Print (msg)

if __name__ = = ' __main__ ':
T1 = Teacher ("Alex", page, ' Python ', 20000)
T2 = Teacher ("Tenglan", +, ' Linux ', 3000)

S1 = Student ("Qinghua", "Python S12", 1483)
S2 = Student ("Sanjiang", +, "Python S12", 1484)

T1.teaching ()
T2.teaching ()
T1.tell ()

polymorphic

Polymorphism (POLYMORPHISN) is a technique that allows you to set a parent object to be equal to one or more of his child objects, after which the parent object can operate differently depending on the attributes of the child object currently assigned to it. To put it simply, it is a sentence: A pointer to the parent class type is allowed to be assigned a pointer to the child class type.
So what is the role of polymorphism? We know that encapsulation can hide implementation details and make code modular; Inheritance can extend existing code modules (classes); they are all designed to-code reuse. And polymorphism is for another purpose--interface reuse! The role of polymorphism is to ensure that classes are called correctly when inheriting and deriving a property of an instance of any class in the family tree.

Class Animal:
def __init__ (self, name): # Constructor of the class
Self.name = Name
Def talk (self): # Abstract method, defined by convention only
Raise Notimplementederror ("subclass must implement abstract method")

Class Cat (Animal):
Def talk (self):
Return ' meow! '

Class Dog (Animal):
Def talk (self):
Return ' woof! woof! '

Animals = [Cat (' Missy '),
Dog (' Lassie ')]

For animal in animals:
Print Animal.name + ': ' + animal.talk ()

Python notes basic article-day6

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.