Python Learning: 14.Python object Oriented (i)

Source: Internet
Author: User
Tags ming

Introduction of Object-oriented

At the beginning of the Python design, it was an object-oriented language, everything in Python, and creating an object in Python was simple, and today we're going to learn about Python's object-oriented knowledge.

Two ways of programming

In C #, Java, you can use object-oriented programming only, and in Ruby, Python, you use functional programming and object-oriented programming.

Function-Type programming

def Fetch (BACKEND):     Pass def Add_record (Backend,record):     Pass Fetch ("www.oldboy.org") Add_record ("  www.oldboy.org", xxxxx)

Object-Oriented Programming

class Oldboy:# class, used to encapsulate several functions    def Fetch (self,backend):#Selfis internal to Python, the user when we pass the value         Pass        #传的The first parameter directly to backend         def  Add_record (self, Backend,record):        pass= Oldboy () obj.fetch ()

Functions are called functions outside of the class, and in the case of the class are called methods, and object-oriented cases where you want to execute a function, you need to create an object from that class and access the function through the object.

Functions of general functional programming are members of a module, while object-oriented programming, a class is a member of a module, a function is a member of a class.

Object-oriented program design is the core of the object (God-like thinking), to understand what the object is, we must regard themselves as God, God in the eyes of the world exists in all things are objects, not exist can also be created. An object is a combination of features and skills, where features and skills correspond to the object's data properties and method properties.
The advantage is that it solves the extensibility of the program. A single modification of an object is immediately reflected in the entire system, such as the character of a character parameter in the game and the ability to modify it easily.
Cons: Poor controllability, inability to process-oriented programming pipelining can accurately predict the problem of the processing process and results, the object-oriented program once started by the interaction between the object to solve the problem, even God can not predict the end result. So we often see a game of people changes in a certain parameter is likely to lead to the ability of the bully to appear, a knife to kill 3 people, the game is out of balance.

Third, object-oriented depth analysis

1. Analysis of Self

2. Encapsulation

classOldboy:deffetch (self):Print(Self.backend)#because the argument self passes the value to the object obj1, you can use self instead of obj1     defAdd_record (Self,record):Passobj1=Oldboy () obj1.backend="Alexsel"#This parameter, together with Obj1, is stored in memory#The non-mainstream way of encapsulationObj1.fetch ()#because backend and obj1 memory together, so do not have to pass the backend, directly            #use Self.backend in a functionObj2=Oldboy () obj2.backend="Alexsel"Obj2.fetch ()

It also shows the function of self, the self can identify the object, due to the two objects passed in the parameters of different, call the method of the class, the output of the content is different, this is the function of self.

Application:
When several functions are to be passed together, the package is relatively simple

3. Construction Method __init__

When creating an object using a class (obj = Foo ()), the __init__ method is executed by default

classFoo:def __init__(Self, BK):##这个self为创建的对象, __init__ is executed by default when an object is created        Print("Init")##所以可把需要多次传的参数在这里创建, replace the one above.Self.name ="Alex"  ##非主流的方法Self.favor =BKPrint(Self.favor)#Create objects, instances, and encapsulate "xxx" into an objectObj1 = Foo ("XXX")#when the object is created, the __init__ method (function) is executed in the class, and this xxx is passed into the BK parameter of the __init__Obj2 = Foo ("SSS") Output Result: Initxxxinitsss

Usage Scenario: When a method of the same type has the same parameters, it is encapsulated directly into the object.
Usage Scenario: Use a class as a template to create multiple objects (the data encapsulated within the object can be different).

Iv. hands-on exercises

For the knowledge we have just learned, we do a simple exercise, output the same results, different two kinds of writing, familiar with the use of methods and properties in the class.

Writing one:

classactivity:def __init__(Self,name,age,gender): self. Flyanaeroplane="{: S},{:s},{:s}, to fly a plane". Format (Name,age,gender) self. Gotoschool="{: s},{:s},{:s}, go to school". Format (Name,age,gender) self. Farm="{: s},{:s},{:s}, go to farming". Format (name,age,gender)defFlyanaeroplane_one (self):Print(self.) Flyanaeroplane)defGotoschool_one (self):Print(self.) Gotoschool)defFarm_one (self):Print(self.) Farm) obj= Activity ("Alexsel","Ten","male") obj. Flyanaeroplane_one () obj. Gotoschool_one () obj. Farm_one () Obj2= Activity ("Eric"," -","male") Obj2. Flyanaeroplane_one () obj2. Gotoschool_one () obj2. Farm_one () Output result: Alexsel,10, man, to fly a plane Alexsel,10, male, go to school Alexsel,10, male, to farm Eric,60, man, Go Fly, Eric,60, male, go to school Eric,60, male, go to farming

Two:

classFoo:def __init__(self, name, age, gender): Self.name=name Self.age=Age Self.gender=GenderdefKaifeiji (self):Print("%s,%s-year-old,%s, to fly a plane"%(Self.name, Self.age, Self.gender))defQuxuexiao (self):Print("%s,%s-year-old,%s, go to school"%(Self.name, Self.age, Self.gender))defQuzhongtian (self):Print("%s,%s years old,%s, go to farming"%(Self.name, Self.age, Self.gender)) Alexsel= Foo ('Alexsel', 10,'male') Alexsel.kaifeiji () Alexsel.quxuexiao () Alexsel.quzhongtian () Eric= Foo ('Eric', 90,'male') Eric.kaifeiji () Eric.quxuexiao () Eric.quzhongtian () output: alexsel,10-year-old, male, to fly alexsel,10-year-old, male, to school alexsel,10-year-old, male, Go to farming eric,90 years old, male, to fly a plane eric,90 years old, male, go to school eric,90 years old, male, go to farming

V. Project exercises

Before writing this project, let's first learn about the Pickel module.

Pickle can serialize any data type, pickle can only be used in Python, the Pickle module is used to serialize the Python object in memory into a byte stream and can be written to any similar file object; it can also be deserialized based on the serialized byte stream. Restores a byte stream to an in-memory object.

Pickle uses the Dump method to serialize memory objects:

Import= List (range (1,3= open ('pickle_list')  wb')    #必须以2进制打开文件, otherwise pickle cannot serialize the object only Pickle.dump (Li, DBFile) dbfile.close () 

The above code will serialize the list object Li to the file "Pickle_list", the next time you run it again, you can restore the list object through the Pickle Load method:

Import= open ('pickle_list'rb'= pickle.load (DBFile) dbfile.close ()

Start a project exercise

ImportPickleclassPerson :def __init__(self,name,age,weight): self. Name=name self. Age=Age self . Weight=WeightdefEat (self): self. Weight= self. Weight + 2#every meal, weight plus 1.    defFitness (self): self. Weight= self. Weight-1#weight Loss of 1 per workoutxiaoming= Pickle.load (Open ("Fitnessgame.obb","RB"))ifXiaoming:#determine if there is a small Ming object, not the one that created Xiaoming    Print(xiaoming. Weight) xiaoming.fitness () xiaoming.fitness () xiaoming.fitness ()Print(xiaoming. Weight) Pickle.dump (Xiaoming,open ("Fitnessgame.obb","WB"))Else: Xiaoming= Person ("Xiao Ming","10 years old", 200) xiaoming.fitness () xiaoming.eat () xiaoming.eat () xiaoming.eat () xiaoming.eat ()Print(xiaoming. Weight) Pickle.dump (Xiaoming,open ("Fitnessgame.obb","WB"))

Tomorrow we're going to talk about object-oriented, and continue to talk about object-oriented inheritance tomorrow.

Python Learning: 14.Python object Oriented (i)

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.