Python Learning Note (vi) Object-oriented

Source: Internet
Author: User
Tags ming

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.

Write base code from top to bottom according to business logic. 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 calls the method here is determined before it is compiled, and the object that the reference points to can be dynamically bound during the run.

Two, object-oriented three major features: encapsulation, inheritance and polymorphism 1. Package

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.

Many classes tend to create objects with an initial state. So the class might define a special method (constructor) named __init__ (), like this:

>>> class Foo:    def __init__ (self,name,age):   #构造方法, automatically executes self.name when an object is created by class        = name        Self.age = age>>> obj1 = foo (' xiaoming ', ' s ') #将小明和12放到obj1/self's name and age >>> obj2 = foo (' Floret ', ten) #self is a formal parameter when executing obj1 = When Foo (' Xiaoming ', 12), self equals obj1  when executing obj2 = Foo (' Floret ', 10), Self equals obj2>>> print (obj1) <__main__. Foo object at 0x0000000003164a90> #内存地址 # directly invokes the encapsulated content through the object. Property name >>> print (obj1.name) xiaoming >>> print ( Obj1.age) 12>>> print (obj2.name,obj2.age) Floret 10

#通过self间接调用被封装的内容

#执行类中的方法时, 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 (' Xiao Ming ', 12)

Obj1.detail () # Python will pass obj1 to the self parameter by default, i.e. Obj1.detail (OBJ1), so the self = Obj1 inside the method, that is: Self.name is xiaoming; Self.age is 12

Methods of the class:

#!/usr/bin/python3    #类定义  class people:      #定义基本属性      name = ' Age      = 0      #定义私有属性, private properties cannot be accessed directly outside the class      __weight = 0      #定义构造方法      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))    # instantiation class  P = people (' Xiao Ming ', 10,30)  p.speak () print (p.weight)

2. Inheritance

It can use all the functionality of an existing class and extend these capabilities without rewriting the original class

#!/usr/bin/python3    #类定义  class people:      #定义基本属性      name = ' Age      = 0      #定义私有属性, private properties cannot be accessed directly outside the class      __weight = 0      #定义构造方法      def __init__ (self,n,a,w):          self.name = n          self.age = a          self.__weight = w< C12/>def Speak (self):          print ("%s" says: I'm%d years old.) "% (self.name,self.age))    #单继承示例  class Student (people):      grade ="      def __init__ (self,n,a,w,grade ):          #调用父类的构函          people.__init__ (self,n,a,w)          Self.grade = Grade    #覆写父类的方法      def speak (self):          print ("%s said: I'm%d years old, I'm reading grade%d"% (self.name,self.age,self.grade)) s = student (' Ken ', 10,60,3)  S.speak ()
 1 class Schoolmember (object): 2 members = 0 #初始学校人数为0 3 def __init__ (self,name,age): 4 Self.name = Name 5         Self.age = Age 6 7 def tell (self): 8 pass 9 def enroll (self): 11 ' Registration ' 12 Schoolmember.members +=113 Print ("\033[32;1mnew member [%s] is Enrolled,now there was [%s] members.\033[0m"% (SE lf.name,schoolmember.members) (__del__) (self): 16 "" Destruction Method "" Print ("\033[31;1mmember [%s ] is dead!\033[0m "%self.name) class Teacher (Schoolmember): def __init__ (self,name,age,course,salary): s Uper (teacher,self). __init__ (name,age) self.course = Course22 self.salary = salary23 Self.enroll ( ) def teaching (self): 27 "Teaching Method" "Print (" Teacher [%s] is teaching [%s] for class [%s] "% ( Self.name,self.course, ' S12 ') (Def Tell): 31 "Self-Introduction method" "+ msg =" "Hi, my name is [%s], wor KS for [%s] as a [%s] TeAcher "% (self.name, ' Oldboy ', Self.course)" Print (msg) "Student" (schoolmember): def __init__ (s  Elf, Name,age,grade,sid): PNs Super (Student,self) __init__ (name,age) Self.grade = Grade39 Self.sid = Sid40 Self.enroll (): 44 "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__ ': 49  T1 = Teacher ("Alex", "the", "Python", 20000) t2 = Teacher ("Tenglan", "Linux", "up") S1 = Student ("Qinghua",     "Python S12", 1483) s2 = Student ("Sanjiang", "57", "Python S12", 1484) t1.teaching () t2.teaching () T1.tell ()

When inheriting initialization properties from a parent class in multiple inheritance, the order is initialized from left to right, as long as the initialization to the property data is no longer backward, so the farther forward the precedence is, when the parent class has initialization, the subclass also has initialization, and the parent class does not take effect.

# class Inheritance-Multiple inheritance class people (object):       #新式类    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):             #多继承    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 ("Lianzh Ilie "," W1 = Woman ("Alex") m1.make_friends (W1) #lianzhilie is making friends with Alex

Classic class and new class, literally can see an old a new, new inevitably contain with many functions, is also recommended after the wording, from the wording of the words, if the current class or the parent class inherits the object class , then the class is a new class, otherwise it is the classic class.

#经典类 class A ():    def __init__ (self):        print ("a") class B (a):    Pass Class C (a):    def __init__ (self):        Print ("C") class D (b,c):    Pass obj = D () #A  #新式类 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

The classic class is in Python2. Depth first in X, new class breadth first.

3. 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. Pyhon does not directly support polymorphism, but can be implemented indirectly.

#多态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!

Python Learning Note (vi) Object-oriented

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.