Python-Day6 oriented, python-day6

Source: Internet
Author: User

Python-Day6 oriented, python-day6
1. process-oriented vs. object-orientedProgramming Paradigm

Programming is the process in which programmers use code consisting of specific syntaxes, data structures, and algorithms to tell computers how to execute tasks, A program is a set of commands compiled by programmers to get the results of a task. There are many different ways to implement a task, summarize the features of these different programming methods, that is, the programming paradigm. Different programming paradigms essentially represent different ideas for solving problems for various types of tasks. Most languages only support one programming paradigm, and of course some languages support multiple programming Paradigms at the same time. The two most important programming paradigms are process-oriented and object-oriented programming.

Procedural Programming)

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

Write base code from top to bottom based on business logic. The basic design idea is that the program starts to solve a big problem at the beginning, and then breaks down a big problem into many small problems or sub-processes, these sub-processes are re-executed and then decomposed until small issues are simple enough to be resolved within a small step.

The problem is also obvious, that is, if you want to modify the program, you must modify all the dependent parts of the modified part. For example, if you set a variable value of 1 at the beginning of the program, but other sub-processes depend on this variable of 1 to run normally, if you change this variable, then you need to modify this sub-process. If another sub-program depends on this sub-process, it will have a series of effects. As the program grows bigger, the maintenance of this programming method becomes more and more difficult. Therefore, we generally think that if you only write some simple scripts to do some one-time tasks, it is excellent to use the process-oriented approach, but if the tasks you want to handle are complex, in addition, it is most convenient to use object-oriented methods to continuously iterate and maintain them.

Object-Oriented Programming

OOP programming uses "Classes" and "objects" to create various models to describe the real world, the reason for using object-oriented programming is that it can simplify program maintenance and expansion, and greatly improve program development efficiency, object-oriented Programs make it easier for people to understand your code logic, making it easier for teams to develop.

The core features of object-oriented are as follows:

Class
A class is the abstraction, blueprint, and prototype of a class of objects with the same attributes. Classes define all the attributes of these objects (variables (data) and common methods.

Object
An object is an instance after a class is instantiated. 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 attributes, just like humans refer to everyone, and each person refers to a specific object. People have similarities and differences with people before.

Encapsulation
The value assignment and internal call of data in the class are transparent to external users. This makes the Class A capsule or container, which contains the data and methods of the class.

Inheritance
A class can be derived from a subclass. The attributes and methods defined in this parent class are automatically inherited by the quilt class.

Polymorphism
The State is an important feature of object orientation. Simply put, "one interface and multiple implementations" means that different subclasses are generated in a base class, each subclass inherits the same method name and implements different methods of the parent class. This is the form of the same thing.
Programming is actually a process of abstracting the specific world. polymorphism is an embodiment of abstraction. It abstracts the commonalities of a series of specific things, and then through this abstract things, dialog with different things.
Sending the same message to different classes of objects will have different behaviors. For example, if your boss asks all employees to start working at nine o'clock, he only needs to say "start working" at nine o'clock, instead of saying: "Start a sales job", said to the technical staff: "Start a technical job", because "employees" are abstract things and can start work as long as they are employees, he knows this. As for each employee, of course, they will perform their respective jobs.
Polymorphism allows the subclass object to be used as the parent class object. A reference of a parent class points to its child type object, and the method called is the child type method. The reference and call method code are determined before compilation, and the referenced object can be dynamically bound during running.

2. Three main features of object-oriented: encapsulation, inheritance and polymorphism 1. Encapsulation

Encapsulation is better understood. Encapsulation is one of the characteristics of object-oriented, and is the main feature of object and class concepts.

Encapsulation refers to encapsulating objective objects into abstract classes. classes can only perform trusted class or object operations on their own data and methods to hide untrusted information.

 

Many classes tend to create objects in the initial state. Therefore, the class may define a special method (constructor) named _ init _ (), as shown below:

>>> Class Foo: def _ init _ (self, name, age): # constructor. self is automatically executed when an object is created based on the class. name = name self. age = age >>> obj1 = Foo ('xiaoming ', 12) # Place the tips and 12 in the name and age of obj1/self >>> obj2 = Foo ('xiaohua ', 10) # self is a form parameter, when obj1 = Foo ('xiaoming ', 12) is executed, self is equal to obj1. When obj2 = Foo ('xiaohua', 10) is executed, self is equal to obj2 >>> print (obj1) <__ main __. foo object at 0x00000000000004a90> # Memory Address # encapsulate the content by calling the object directly. attribute name >>> print (obj1.name) Xiaoming >>> print (obj1.age) 12 >>> print (obj2.name, obj2.age) Xiaohua 10

# Indirectly calling encapsulated content through self

# When executing methods in the class, the encapsulated content needs to be indirectly called through self

 

Class Foo:

    def __init__(self,name,age):        self.name = name        self.age = age

Def detail (self ):
Print self. name
Print self. age

Obj1 = Foo ('xiaoming ', 12)

Obj1.detail () # by default, Python will pass obj1 to the self parameter, that is, obj1.detail (obj1). Therefore, the self = obj1 in the method is self. the name is James; self. age is 12

Class method:

#! /Usr/bin/python3 # class definition class people: # define basic property name = ''age = 0 # define private property, private attributes cannot be directly accessed outside the class _ weight = 0 # define the constructor def _ init _ (self, name, age, weight): self. name = name self. age = age self. _ weight = weight def speak (self): print ("% s said: I'm % d years old. "% (Self. name, self. age) # instantiate class p = people ('xiaoming ',) p. speak () print (p. weight)

 

2. Inheritance

It can use all the functions of existing classes and extend these functions without re-writing the original classes.

 

#! /Usr/bin/python3 # class definition class people: # define basic property name = ''age = 0 # define private property, private attributes cannot be directly accessed outside the class _ weight = 0 # define the constructor def _ init _ (self, n, a, w): self. name = n self. age = a self. _ weight = w def speak (self): print ("% s: I % d years old. "% (Self. name, self. age) # class student (people): grade = ''def _ init _ (self, n, a, w, grade ): # Call the structure people of the parent class. _ init _ (self, n, a, w) self. grade = grade # override the parent class method def speak (self): print ("% s said: I'm % d years old, I'm in % d grade" % (self. name, self. age, self. grade) s = student ('ken', 10, 60, 3) s. speak ()
1 class SchoolMember (object): 2 members = 0 # the initial number of students is 0 3 def _ init _ (self, name, age): 4 self. name = name 5 self. age = age 6 7 def tell (self): 8 pass 9 10 def enroll (self): 11 '''register ''' 12 SchoolMember. members + = 113 print ("\ 033 [32; 1 mnew member [% s] is enrolled, now there are [% s] members. \ 033 [0 m "% (self. name, SchoolMember. members) 14 15 def _ del _ (self): 16 ''' destructor ''' 17 print ("\ 033 [31; 1 mmember [% s] is de Ad! \ 033 [0 m "% self. name) 18 class Teacher (SchoolMember): 19 def _ init _ (self, name, age, course, salary): 20 super (Teacher, self ). _ init _ (name, age) 21 self. course = course22 self. salary = salary23 self. enroll () 24 25 26 def teaching (self ): 27 ''' teaching Method ''' 28 print ("Teacher [% s] is teaching [% s] for class [% s]" % (self. name, self. course, 's12') 29 30 def tell (self): 31 ''' self-introduction method ''' 32 msg = ''' Hi, my name is [% s], works For [% s] as a [% s] teacher! ''' % (Self. name, 'oldboys', self. course) 33 print (msg) 34 35 class Student (SchoolMember): 36 def _ init _ (self, name, age, grade, sid): 37 super (Student, self ). _ init _ (name, age) 38 self. grade = grade39 self. sid = sid40 self. enroll () 41 42 43 def tell (self): 44''' self-introduction method ''' 45 msg = ''' Hi, my name is [% s], i'm studying [% s] in [% s]! ''' % (Self. name, self. grade, 'oldboys') 46 print (msg) 47 48 if _ name _ = '_ main _': 49 t1 = Teacher ("Alex", 22, 'python', 20000) 50 t2 = Teacher ("TengLan", 29, 'linux ', 3000) 51 52 s1 = Student ("Qinghua", 24, "Python S12 ", 1483) 53 s2 = Student ("SanJiang", 26, "Python S12", 1484) 54 55 t1.teaching () 56 t2.teaching () 57 t1.tell ()Inherited instance

In multi-inheritance, when the initialization attribute is inherited from the parent class, the initialization sequence starts from left to right. As long as the attribute data is initialized, the initialization will not proceed backward. Therefore, the more advanced the initialization is, the more advanced the initialization is. When the parent class has initialization, when a subclass is initialized, the initialization of the subclass is executed. The parent class does not take effect.

# Class inheritance-Multi-inheritance class People (object): # New class def _ init _ (self, name, age): self. name = name self. age = age def eat (self): print ("% s is eating... "% self. name) def sleep (self): print ("% s is sleeping .... "% self. name) class Relation (object): def make_friends (self, obj): print ("% s is making friends with % s" % (self. name, obj. name) class Man (Relation, People): # multiple inheritance def play (self): print ("% s is playing .... "% self. name) class Woman (People): def get_birth (self): print ("% s is born a boby .... "% self. name) m1 = Man ("lianzhilie", 22) w1 = Woman ("Alex", 33) m1.make _ friends (w1) # lianzhilie is making friends with Alex

Classic class and new style class can be seen from the literal sense that a new and old class will inevitably contain many features and will also be recommended later.The current class or parent class inherits the object class.The class is a new type, otherwise it is a classic type.

# Classic class A (): def _ init _ (self): print ("A") class B (A): pass class C (): def _ init _ (self): print ("C") class D (B, C): pass obj = D () # A # New class A (object): def _ init _ (self): print ("A") class B (A): pass class C (A): def _ init _ (self ): print ("C") class D (B, C): pass obj = D () # C

In python2.X, the classic category takes precedence over the new category.

3. Polymorphism

Polymorphisn is a technology that allows you to set a parent object to be equal to one or more of its sub-objects, the parent object can operate in different ways based on the features of the sub-objects assigned to it. To put it simply, you can assign a pointer of the subclass type to a pointer of the parent class. So what is the role of polymorphism? We know that encapsulation can hide implementation details to modularize the code. inheritance can expand existing code modules (classes). They are all for the purpose of code reuse. Polymorphism aims to achieve another purpose-interface reuse! Polymorphism is used to ensure that a certain attribute of an instance of any type in the family tree is called correctly when the class is inherited and derived. Pyhon does not directly support polymorphism, but can be indirectly implemented.

# Polymorphism class Animal: def _ init _ (self, name): # Constructor of the class self. name = name @ staticmethod def animal_talk (obj): obj. talk () class Cat (Animal): def talk (self): print ('% s: Meow! '% (Self. name) class Dog (Animal): def talk (self): print (' % s: Woof! Woof! '% (Self. name) c = Cat ('missy ') d = Dog ('Lassie') Animal. animal_talk (c) Animal. animal_talk (d) # Missy: Meow! # Lassie: Woof! Woof!

 

Related Article

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.