Python learning-Object oriented 1

Source: Internet
Author: User

Reference: http://www.cnblogs.com/wupeiqi/

Overview

Python is programmed in three different ways

    • Process-oriented: Write code from top to bottom line based on business logic
    • Function: To encapsulate some functions in a function, you need to call only the function
    • Object-oriented: Re-encapsulation and classification of functions for easier development

Object-oriented programming is a way of programming, which requires "classes" and "objects" to be implemented, so object-oriented programming is actually the use of "classes" and "objects".

    • A class is a template that can contain multiple functions and functions in a template.
    • Objects are instances created from templates that can execute functions in a class through an instance object
Creating Classes and objects
    • Class is the keyword for the classes, representing the class, as the DEF is the function's keyword, representing the function
    • Creating an object is also called instantiation of the class, which is followed directly by the class ()
    • method is the function defined in the class
# Create Class class Foo (object):     """ The     help    for Class ""     #  creates a function in a class    # self for special parameters, required     def  func (self):        pass#  creates an object based on class Foo objobj = Foo () # Call the Func method Obj.func ()

Functional programming is easier than object-oriented when executing a method (function) through functional programming and object-oriented programming

Object-oriented:

    • Creating objects
    • Method by Object execution

Function Type:

    • Execute function

The application scenario for functional programming is a separate, non-pooled data between functions

Three main features of object-oriented

The three main characteristics of object-oriented are: encapsulation, inheritance and polymorphism

First, the package

Encapsulation is the method, fields, attributes and other information collectively encapsulated in a place, convenient to call later

1, the method, fields, attributes and other information encapsulation

#Create ClassclassFoo (object):#constructs a method that automatically executes when an object is created according to a class    def __init__(self, Name, age): Self.name=name Self.age= Age#create an object from class Foo obj1Obj1 = Foo ('Wenchong', 10)#create an object from class Foo Obj2Obj2 = Foo ('Alan', 10)

Self is a formal parameter

When executing obj1 = Foo (' Wenchong ', 10), self = obj1

When executing obj2 = Foo (' Alan ', 10), self = obj2

Content is encapsulated in Obj1 and Obj2, both Obj1 and OBJ2 have name and age two properties

2. Call the encapsulated content

There are two ways to invoke the encapsulated content

    • Called directly through an object
    • Indirectly called through self
#Create ClassclassFoo (object):#constructs a method that automatically executes when an object is created according to a class    def __init__(self, Name, age): Self.name=name Self.age= Age#create an object from class Foo obj1Obj1 = Foo ('Wenchong', 10)Print(Obj1.name)#call the Name property of Obj1 directlyPrint(Obj1.age)#Call Obj1 's age property directly#create an object from class Foo Obj2Obj2 = Foo ('Alan', 10)Print(Obj2.name)#call the Name property of Obj2 directlyPrint(Obj2.age)#Call Obj2 's age property directly
#Create ClassclassFoo (object):#constructs a method that automatically executes when an object is created according to a class    def __init__(self, Name, age): Self.name=name Self.age= AgedefShow (self):Print(Self.name)Print(self.age)#create an object from class Foo obj1Obj1 = Foo ('Wenchong', 10)#by calling the Show method, the first argument of the Show method is self = obj1, which is self.name = ' Wenchong ', self.age = tenobj1.show ()#create an object from class Foo Obj2Obj2 = Foo ('Alan', 10)#by calling the Show method, the first argument of the Show method is self = obj2, which is self.name = ' Alan ', self.age = tenObj2.show ()
Ii. inheritance

One of the main benefits of object-oriented programming is the reuse of code, and one way to implement this reuse is through inheritance mechanisms. Inheritance can be fully understood as a type and subtype relationship between classes.

For object-oriented, it is to extract the methods of multiple subclasses into the parent class, the subclass only inherits the method of the parent class, and does not need one by one implementation

inherited syntax

class Child Class (parent class [, parent Class 1, parent Class 2 ...]):     Pass

Single inheritance

When a subclass inherits a parent class, if there is no called method in the child class, it is found in the parent class, and if not in the parent class, it continues to be found in the parent class's parent class.

#Create a animal class that contains common methods for cat and dogclassAnimal (object):defEat (self):Print('%s Eat'%self.name)defDrink (self):Print('%s Drink'%self.name)defshit (self):Print('%s Pull'%self.name)defpee (self):Print('%s Caesar'%self.name)#Create a cat class that contains only the cat-unique methodsclassCat (Animal):def __init__(self, name): Self.name=name Self.breed='Cat'    defCry (self):Print('Meow Meow')#Create a dog class that contains only the methods that are unique to dogclassDog (Animal):def __init__(self, name): Self.name=name Self.breed='Dog'    defCry (self):Print('Barking')#creates an object from a class and executesCat = Cat ('Small White House of Little black Cat') Cat.cry () cat.eat () Cat.drink ( )

Multiple inheritance

When a subclass inherits multiple parent classes, it is called multiple inheritance

classA (object):defFoo2 (self):Print('A')classB (A):deffoo1 (self):Print('B')classC (B):deffoo1 (self):Print('C')classD (A):defFoo2 (self):Print('D')classE (D):deffoo1 (self):Print('E')classF (C, E):deffoo1 (self):Print('F') obj=F () Obj.foo2 ()

The last output in the example above is D

When a subclass inherits multiple parent classes, the way to look for methods follows the C3 algorithm, which is the order in which the method is found in the parent class

Python 2.x is different

Python 2.7 is divided into breadth-first algorithm and depth-first algorithm

    • When a class is a classic class, multiple inheritance cases are searched in the depth-first way
    • When a class is a new class, in multiple inheritance cases, the breadth-first method is found

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.

Three, polymorphic

Multiple forms

classF1:PassclassS1 (F1):defShow (self):Print 'S1.show'classS2 (F1):defShow (self):Print 'S2.show'defFunc (obj):Printobj.show () s1_obj=S1 () Func (s1_obj) s2_obj=S2 () Func (s2_obj)
Add

Storage of classes and objects in memory

As shown, when you create an object from a class, the object, in addition to encapsulating the value of name and age, holds a class object pointer that points to the class of the current object.

When "method One" is executed through OBJ1, the process is as follows:

    1. Finds a method in a class based on the pointer to a class object in the current object
    2. Obj1 the object as a parameter to the first argument of the method self

Python learning-Object oriented 1

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.