Python path, day6-object-oriented

Source: Internet
Author: User

First, process-oriented programming

Simply put: If you're just writing some simple scripts to do some one-off tasks, it's great to use a process-oriented approach, but if you're dealing with a complex task that needs to be iterative and maintainable, it's the most convenient thing to do with object-oriented.

Second, object-oriented programming

Class: Classes

A class is an abstraction, a blueprint, a prototype for a class of objects that have the same properties. The properties of these objects (variables (data)) and common methods are defined in the class.

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 invokes the method is already determined before it is compiled, and the object pointed to by the reference can be dynamically bound during run time

"Class" Example:

classRole (object):def __init__(self,name,role,weapon,life_value=100,money=15000): Self.name=name Self.role=role Self.weapon=Weapon Self.life_value=Life_value Self.money= MoneydefShot (self):Print("Shooting ...")     defGot_shot (self):Print("Ah...,i got shot ...")     defBuy_gun (self,gun_name):Print("just bought%s"%gun_name) R1= Role (' Liudong','Police','AK47 ') #生成一个角色r2 = Role ('Jack','Terrorist','B22 ') #生成一个The above code is explained:classRole (object):#   defines a class, which is the syntax for defining a class, role is the class name, and (object) is the style of the new class, which must be written, and then why    
 def__init__ (self,name,role,weapon,life_value=100,money=15000): #   initialization function, some properties to initialize when generating a role are filled in here  self.name = name  #  __init__ is self, and the self here is What is the meaning? See below for an explanation of  self.role = role self.weapon  = weapon self.life_value  = Life_value Self.money  = Money 

r1=   Role ( ' Alex ' ' police ' #生成一个角色, the parameters are automatically passed to the __init__ under role ( ...) Method
r2  = Role( ‘Jack‘ , ‘terrorist‘ ,‘B22’)   #生成一个角色 r1  = Role( ‘liudong‘ , ‘police‘ , ‘AK47’) #此时self 相当于 r1 ,  Role(r1,‘liudong ‘,‘ police ‘,‘ AK47’) r2  = Role( ‘Jack‘ , ‘terrorist‘ , ‘B22’)#此时self 相当于 r2, Role(r2,‘ Jack ‘,‘ terrorist ‘,‘ B22’)

Packaging:

classRole (object): a='Liudong'b='Test'    def __init__(self,name,role,weapon,life_value=100,money=15000): Self.name=name Self.role=role Self.weapon=weapon Self.__life_value=Life_value Self.money= MoneydefShot (self):Print("Shooting ...")    defLife_status (self):Print("name:%s weapon:%s life_val:%s"%(Self.name, Self.weapon, Self.__life_value                                                        ))    defGot_shot (self):Print("Ah...,i got shot ...")    defBuy_gun (self,gun_name):Print("%s just bought%s"%(self.name,gun_name)) R1= Role ('Liudong','Police','AK47',)#generate a roleR1.a=1R2= Role ('Jack','Terrorist','B22',)#generate a roler2.b=2delr2.br2.got_shot () R2.buy_gun ('AK47')Print(R1.a,r2.a,r1.money,)Print(R1.life_status ())Print(r1.b,r2.b)

Inherited:

classpeople ():def __init__(self,name,age): Self.name=name Self.age= AgedefPiao (self):Print("----------------")classMan (people):defPiao (self): People.piao (self)Print("%s is piaoing ....."%Self.name) M1=man ("hehe", 22) M1.piao ()

Multi-Episode process:

#py3-Classic class and new class are-breadth First py2-Classic class is press-depth first------New class is press-breadth firstclassSchool (object):def __init__(SELF,NAME,ADDR): Self.name=name Self.addr=addr Self.students=[] self.staffs=[]    defEnroll (self,stu_obj):Print("register for student%s"%stu_obj.name) self.students.append (stu_obj)defHire (self,staff_job): Self.staffs.append (staff_job)Print("Hire New Employee%s"%staff_job.name)classSchoolmember (object):def __init__(self,name,age,sex): Self.name=name Self.age=Age Self.sex=SexdefTell (self):PassclassTeacher (schoolmember):def __init__(Self,name,age,sex,salary,course): Super (teacher,self).__init__(name,age,sex) self.salary=Salary Self.course=CoursedefTell (self):defTeach (self):Print("%s is teaching course [%s]"%(self.name,self.course))classStudent (schoolmember):def __init__(Self,name,age,sex,stu_id,grade): Super (student,self).__init__(name,age,sex) self.stu_id=stu_id Self.grade=GradedefTell (self):Print(" "----------------------------------------------------name:%s age:%s sex:%s stu_id :%s grade:%s" "%(Self.name, Self.age, Self.sex, self.stu_id, Self.grade))defpay_tuition (self,amount):Print("%s has paid tution for $%s"%(Self.name,amount)) school= School ("old boy It","Shahe") T1= Teacher ("Oldboy"," About","M","20000000","Linux") T2= Teacher (" Liu Dong"," at","M","100000000000","python") S1= Student ("Zhang San"," -","F","1001","Pythondevops") S2= Student ("John Doe"," -","M","1002","Linux") T1.tell () S1.tell () school.hire (T1) school.enroll (S1) school.enroll (S2)Print(school.students)Print(school.staffs) School.students[0].teach () forStuinchSchool.students:stu.pay_tuition (5000)

Python path, day6-object-oriented

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.