Python full stack Development Road "seventh": Object-oriented programming design and development

Source: Internet
Author: User

The content of this section, programming paradigm

Programming refers to writing programs, knocking code, refers to the programmer with specific syntax, data structures and algorithms written code, the purpose is to tell the computer how to perform the task.

The two most common genres in the programming world are: process-oriented and object-oriented. "Kungfu schools do not have high and low points, only the martial arts talents have high and low points", in the programming world is so, oriented process and object-oriented in different scenarios have their pros and cons, who good who bad can not generalize.

II. Process-oriented programming

The core is the word "process", "process" refers to the steps to solve the problem, that is, what to do first ..., based on process-oriented design program is like in the design of a pipeline, is a mechanical way of thinking.

Pros: Complex problems are simplified.

#Write a data remote backup program,#three-step, local data package, upload to cloud server, test backup file AvailabilityImportOSdefdata_backup (folder):Print("Locate backup directory:%s"%folder)Print('backing up ...') Zip_file='/tmp/backup20181103.zip'    Print('backup succeeded, backup file is:%s'%zip_file)returnZip_filedefcloud_upload (file):Print("\nconnecting Cloud Storage Center ...")    Print("cloud storage connected.")    Print("upload file...%s...to Cloud ..."%file) Link='http://www.xxx.com/bak/%s'%os.path.basename (file)Print('Close Connection .....')    returnLinkdefdata_backup_test (link):Print("\ n Download file:%s, verify that the file is lossless"%link)defMain ():#Step One: Local data packagingZip_file = Data_backup ("c:\\users\\alex\ Europe 100G HD Uncensored")    #Step two: Upload to cloud serverlink=cloud_upload (zip_file)#Step Three: Test the availability of backup filesdata_backup_test (link)if __name__=='__main__': Main ()
process-oriented examples

Disadvantage: very poor extensibility.

Application Scenarios:

Process-oriented program design ideas are typically used in scenarios where functionality is rarely changed once implemented, and if you're just writing simple scripts to do some one-off tasks, it's great to use a process-oriented approach, with examples of Linux kernel, git, and Apache HTTP server. But if the task you're dealing with is complex and needs to be constantly iterated and maintained, it's the easiest thing to do with object-oriented.

Third, object-oriented programming

The core is the word "object", to understand what the object is, we must regard themselves as God, in the eyes of God, the existence of all things in the world are objects, not exist can also be created, and the process of mechanical mode of thinking in sharp contrast, object-oriented more attention to the real world rather than the simulation of the process, is a "God Way of thinking.

Advantages: High scalability.

Cons: The complexity of programming is much higher than the process-oriented.

Application scenario: Of course, it is applied to the software which frequently changes the demand, the change of the general demand is concentrated in the user layer, the Internet application, the enterprise internal software, the game and so on are the object-oriented programming good place.

Iv. Classes and objects

An object is a combination of features and skills, and a class is a combination of features and skills that resemble a series of objects.

In the real world: Must have the object first, then has the class;

In the program: to define the class first, the resulting object.

Defining classes

Following the above steps, we define a class (we stand in the school's perspective, all of you here are students)

>>> in the real world, there are objects first, then there are classes

Object 1: Lee Tank    features:        school = real        name = Lee Tank        sex = male        age =18    Skill: Learning to eat and        sleep object 2: King Cannon    Features:        School = Real        name = King Cannon        sex = female        age =38    Skill: Learning to eat and        sleep object 3: Cow grenade    characteristics:        School = real        name = Bull Grenade        sex = male        age =78    Skills:        learning to        eat        and sleep reality in the real student class    similar characteristics:        school = Real    similar skills:        learning        Eat and        sleep

>>> in the program, be sure to: Define (Class) First, then use the class (to produce the object)

#在Python中程序中的类用class关键字定义, while in the program the feature is identified with a variable, and the skill is identified with a function, so the most common in the class is nothing more than: the definition of variables and functions class Schoolstudent:    school= ' real '    def Learn (self):        print ("is learning")    Def Eat (self):        print (' was eating ')    def sleep (self):        print (' Is Sleeping ')

Attention:

The ① class can have arbitrary Python code that executes during the definition phase of the class, resulting in a new namespace that holds the class's variable name and function name, which can be viewed through schoolstudent.__dict__.

The names defined in the ② class are the properties of the class, and the point is the syntax for accessing the property of the class.

use of the class

Additions and deletions of class attributes

Schoolstudent.school #查SchoolStudent. school= ' University ' #改SchoolStudent. X=1 #增del schoolstudent.x #删

Call the class, also become instantiated, get the object in the program

S1=schoolstudent () s2=schoolstudent () s3=schoolstudent () #如此, S1, S2, S3 are all the same, and these three have different properties in addition to similar attributes, which is used in __init__

__init__ method

#注意: This method is executed after the object has been generated, only to initialize the object, can have arbitrary code, but must not have a return value # __init__ method used to customize the object unique characteristics class Luffystudents:school = ' Luffycity ' # up and down corresponds to STU1, ' hyp ', ' Man ' def __init__ (self, name, age, Sex): self. Name = Name Self. Age = Age self. sex = sex # is equivalent to #stu1. Name = ' Hyp ' #stu1. Age = #stu1. Sex = "Man" def learn (self): print ("is learning") def eating (self): print (' is eating ') # generates object STU1 = Luffystudents (' Hyp ', +, ' man ') print (STU1) "" "plus the __init__ method, instantiate the steps: 1. First create an empty object Stu1 2.luffystudents.__init__ (STU1, ' Hyp ', ', ' Man ') print (luffystudents.__init__)--Returns the function property of the Class "" # # # Check # print (stu1.__dict__) # Print (STU1. Name) # # # # STU1. Name = ' LCY ' # Print (stu1.__dict__) # Print (STU1. Name) # # # delete # del stu1. name# print (stu1.__dict__) # # # add # stu1.class_name = ' Full stack development ' # Print (stu1.__dict__) "" "#-First produce empty object, then tune __init__, and pass parameters luffystudents.__init__ (STU2, ' LCY ', 22, ' female ') "" "Stu2=luffystudents (' LCY ', 22, ' female ')

Use of objects
#执行__init__, s1.name= ' Bull grenade ', it is also obvious that the object's namespace can be viewed with s2.__dict__, viewing the result as {' name ': ' King Cannon ', ' age ': ' female ', ' sex ': 38}s2.name #查, equivalent to S2 . __dict__[' name ']s2.name= ' Wang San Cannon ' #改, equivalent to s2.__dict__[' name ']= ' Wang San cannon ' s2.course= ' python ' #增, equivalent to s2.__dict__[' course ']= ' Python ' del s2.course #删, equivalent to S2.__dict__.pop (' course ')
Add:

The ① station has different angles, and the defined classes are distinct.

② Real class is not exactly equal to the class in the program, such as the real company class, in the program sometimes need to split into departmental class, business class, etc.

③ sometimes for programming needs, the program may also define a class that does not exist in reality, such as a policy class, which does not exist in reality, but is a common class in the program.

The property lookup and binding method of classproperties of the class:

Divided into Data properties and function properties.

1. The Data property of a class is common to all objects, pointing to the same memory address.

#类的数据属性是所有对象共享的, id all the same print (ID (schoolstudent.school)) print (ID (s1.school)) #4377347328print (ID (s2.school)) # 4377347328print (ID (s3.school)) #4377347328

2. The function property of a class is bound to an object, and is called a method bound to an object.

#类的函数属性是绑定给对象使用的, Obj.method is called a binding method, and the memory address is not the same as print (Schoolstudent.learn) #<function Schoolstudent.learn at 0x1021329d8>print (S1.learn) # Results: <bound method Schoolstudent.learn of #<__main__. Schoolstudentobject at 0x1021466d8>>print (s2.learn) # Result: <bound method Schoolstudent.learn of <__main__. Schoolstudentobject at 0x102146710>>print (s3.learn) # Result: <bound method Schoolstudent.learn of <__main__. Schoolstudentobject at 0x102146748>> #ps: ID is the implementation mechanism of Python and does not really reflect memory address, if there is memory address, or memory address

Note: The obj.name will first find the name in Obj's own namespace, find it in the class, find the class, and find the parent class ... Throw an exception if you can't find it at the end!

Binding Method

Define a class and instantiate three objects first

Class Schoolstudent:    school= ' solid '    def __init__ (self,name,age,sex):        self.name=name        self.age=age        self.sex=sex    def Learn (self):        print ('%s was learning '%self.name) #新增self. Name    def eat (self):        Print ('%s is eating '%self.name)    def sleep (self):        print ('%s is sleeping '%self.name) s1=schoolstudent (' Lee Tank ', ' Male ', S2=schoolstudent (' King Cannon ', ' female ', ' s3=schoolstudent ') (' Bull grenade ', ' male ', 78)

A function defined in a class (not decorated by any adorner) is a function property of a class, which can be used, but must follow the parameters of the function, with several arguments to pass.

Schoolstudent.learn (S1) #李坦克 is Learningschoolstudent.learn (S2) #王大炮 are Learningschoolstudent.learn (S3) #牛榴弹 is Learnings1.learn () #等同于SchoolStudent. Learn (S1) S2.learn () #等同于SchoolStudent. Learn (S2) S3.learn () # Equivalent to Schoolstudent.learn (S3)

The functions defined in the class (which are not decorated by any adorners) are primarily used for objects, and are bound to objects, although all objects point to the same functionality, but binding to different objects is a different binding method.

Emphasize:

The special thing about bound to an object is that the binding to whom it is called, who calls it, will ' who ' itself as the first parameter passed to the method, that is, the automatic value (method __init__ is the same reason)

   This automatic value-passing feature of a method bound to an object determines that functions defined in the class must write a parameter by default self,self can be any name, but it is customary to write self.

class is type

Everything in Python is object, and the class and type in Python3 is a concept, and the type is the class.

#类型dict就是类dict >>> list<class ' list ' > #实例化的到3个对象l1,l2,l3>>> l1=list () >>> l2=list () >>> l3=list () #三个对象都有绑定方法append, is the same function, but the memory address differs >>> L1.append<built-in method Append of the list object At 0x10b482b48>>>> l2.append<built-in method Append of the list object at 0x10b482b88>>>> L3.append<built-in method Append of List object at 0x10b482bc8> #操作绑定方法l1. Append (3), which is adding 3 to L1, will never add 3 to L2 or l3> >> l1.append (3) >>> l1[3]>>> l2[]>>> l3[] #调用类list. Append (l3,111) equivalent to L3.append (111) >>> list.append (l3,111) #l3. Append (111) >>> l3[111]
"""Practice One: Write a student class that produces a bunch of student objects that require: there is a counter (attribute) that counts the total number of objects that have been instantiated"""classStudent:school='luffycity'  #Data PropertiesCount =0def __init__(Self, name, age, Sex):#Class Properties        #Self.count + = 1Self.name =name Self.age=Age Self.sex=Sex Student.count+ = 1#implementing common attribute accumulation        #There are several instances of the object that will accumulate several times    defLearn (self):#Function Properties        Print('%s is learning'%self.name)#instantiation of three objectsSTU1 = Student ('Hyp','male', 18) STU2= Student ('LCY','female', 17) Stu3= Student ('Alex','male', 28)#only the method of counting is reflected to the unique characteristics of each object and cannot be accumulatedPrint(Stu1.count)Print(Stu2.count)Print(Stu3.count)Print(STU1.__dict__)Print(STU2.__dict__)Print(STU3.__dict__)#Print(Student.count)"""Exercise Two: Imitating the glory of kings two hero requirements: Heroes need to have nicknames, attack, health and other attributes, instantiate two heroic objects, heroes can be beaten, the beating of the side of the blood, the blood of less than 0 is judged as death. """classGeren:camp='Demacia'    def __init__(self, nickname, Life_value, aggersivity): Self.nickname=Nickname Self.life_value=Life_value self.aggersivity=aggersivitydefAttack (self, Enemy): Enemy.life_value-=self.aggersivityclassRiven:camp='Demacia'    def __init__(self, nickname, Life_value, aggersivity): Self.nickname=Nickname Self.life_value=Life_value self.aggersivity=aggersivitydefAttack (self, Enemy): Enemy.life_value-=SELF.AGGERSIVITYG1= Geren ('Bush LUN', 100, 30) R1= Riven ('Susan', 80,50) G1.attack (R1)
Little Practice

Python full stack Development Road "seventh": Object-oriented programming design and development

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.