Object-oriented programming of Python

Source: Internet
Author: User

Primary Knowledge class

A class is a collection of objects that describe the same properties and methods. objects are specific, and a class is an abstract concept. In your program, you follow the order in which classes are first defined and then called. Class name is the camel body, class in the definition phase will immediately execute the class body code, the resulting name is stored in the class namespace, you can use __dict__ to view the namespace of the class, the result will be returned as a dictionary.

Classes are divided into parent and child classes. The parent class is also known as a base class or a superclass, and a subclass is also known as a derived class. A class has two properties: Data Properties and Function properties (functions are not decorated by any adorners). The data properties of a class are all shared by direct objects, and the function properties of a class are bound to objects, and binding to different objects is a different binding method.

classStudent:
#定义私有属性, the external cannot directly access n=0
#__init__ () Construction method
#self代表类的实例
#def定义方法, the first parameter of a class method must be the one used to represent the instance of the class .def __init__(self,name,age,gender): Self.name=property references for name# class objects Self.age=Age Self.gender=Gender STUDENT.N+=1School='Red Sun' defLearn (self):return '%s is learning'%Self.name
#obj. Class STU1=student ('AA', 19,'female') #类对象的实例化#print (STU1.N)#print (Stu1.learn)##<bound method Student.learn of <__main__. Student object at 0x000001befd188b38>>#print (Stu1.learn ())STU2=student ('BB', 23,'male')#print (STU2.N)#print (Stu2.learn)##<bound method Student.learn of <__main__. Student object at 0x000001befd188ba8>>#Print (ID (STUDENT.N), STUDENT.N)#Print (ID (STU1.N), STU1.N)#Print (ID (STU2.N), STU2.N)##同id#student.n=1#Print (ID (STUDENT.N), STUDENT.N)#Print (ID (STU1.N), STU1.N)#Print (ID (STU2.N), STU2.N)#are changing with the STUDENT.N .#stu1.n=1#Print (ID (STUDENT.N), STUDENT.N)#Print (ID (STU1.N), STU1.N) #1345678816 1#Print (ID (STU2.N), STU2.N)#only the STU1 changes, the rest is unchanged.

The instantiation of a class is the process of invoking a class to produce an object, which is the result of the instantiation of the class. objects, in addition to common properties and methods, should also be unique, so that objects that instantiate the result of a class are not identical. To make an object characteristic, define a __init__ function within the class that automatically triggers execution when the class is called.

There are three things that happen to the process of invoking a class:

One is to produce empty objects;

The second is the automatic triggering of the __init__ function in the class body;

The third is to pass the empty object along with the arguments in the calling class in parentheses to the __init__ function.

Use of the class:

1. Parameter rules for functions must be followed

2. A function defined in a class is used primarily for objects, and is bound to an object. Although the point of all objects is the same function, binding to different objects is a different binding method. The special thing that binds to an object is who is called by whom, and who invokes it as the first argument (self) to the method, that is, the value is automatically passed.

Interaction between objects

classDog:def __init__(self,name,d_type,aggressivity,life_value): Self.name=name Self.d_type=D_type self.aggressivity=aggressivity Self.life_value=Life_valuedefBite (Self,enemy): Enemy.life_value-=self.aggressivityPrint(" "Dog [%s] bite [%s] person losing blood [%s] The person's health is left [%s ]" "%(self.name,enemy.name,self.aggressivity,enemy.life_value)) Dog1= Dog ('Wong Choy','Chinese Pastoral Dog', 50, 60)classpeople:def __init__(self,name,aggressivity,life_value=100): Self.name=name Self.aggressivity=aggressivity Self.life_value=Life_valuedefBite (Self,enemy): Enemy.life_value-=self.aggressivityPrint(" "person [%s] biting dog [%s] dog losing blood [%s] The dog's health is left. [%s]" "%(Self.name, Enemy.name, Self.aggressivity, Enemy.life_value)) People1=people ('AA', 30) People1.bite (DOG1)

Inheritance and derivation

Inheritance is the relationship between classes and classes, and is a way to create classes that are inherited to reduce code redundancy. Subclasses inherit the attributes of the parent class, and the child class inherits one or more of the parent classes.

The search for an inheritance relationship requires an abstraction before inheriting.

Property Lookup is now from the subclass to find itself, not found again to go to the parent class lookup.

A derivation is a subclass that defines its own new property and, if it is the same as the parent class's property, whichever is the subclass itself. The way in which the parent class function is reused in a new method derived from a subclass: The first is called by names, which is irrelevant to the inheritance relationship, and is the same as calling the normal function, and the second is to get the return value by executing super (), which is a special object that is specifically used to invoke the MRO () The list looks for properties or methods of the next class from the current find location. The second approach is to strictly follow the inheritance relationship.

Combination

1. What is a combination?

A combination is a property that is used to describe an object owned by another class.

2. How does the combination work?

Class school:school= ' red hair ' def __init__ (self,name,age,gender): Self.name=name self.age=age Self.gender=genderclass date:def __init__ (self,year,mon,day): Self.year = Year Self.mon = Mon se   Lf.day = Day def Tell_birth (self): print ("' ========== year [%s] month [%s] Day        [%s] "% (self.year,self.mon,self.day)) class Teacher (School): def __init__ (self,name,age,gender,level,salary): Super ( teacher,self). __init__ (Name,age,gender) #用super () reusing the parent class Self.level=level Self.salary=salary self.courses =[] def change_score (self): print (' teacher was changing score ') def Tell_course_info (self): print (' Tea Cher [%s] has course: '%self.name). Center (+, ' = ')) for course_obj in Self.courses:course_obj.info () #组合c        Lass Student (School): def __init__ (Self,name,age,gender,grade): Super (Student,self). __init__ (Name,age,gender) self.grAde=grade self.courses=[] def choose (self): print (' Student [%s] Choose Course '%self.name) def Tell_cou Rse_info (self): print ((' Student [%s] Learn course: '%self.name '). Center ((+, ' = '))) for Course_obj in Self.course S:course_obj.info () class Course:def __init__ (self,cname,period,price): Self.cname=cname self . Period=period Self.price=price def info (self): print ("' ========course info======== cours E_name <%s> course_period <%s> course_price <%s> '% (self.cname,self.peri Od,self.price) t1=teacher (' AA ', +, ' female ', 9,3.1) # t1.birth=date (1998,12,12) # T1.birth.tell_birth () s1=student (' BB ', +, ' male ', ' Python ') # s1.birth=date (2002,12,12) # S1.birth.tell_birth () python=course (' Python ', ' 5mons ', 20000) Linux=course (' Linux ', ' 5mons ', 20000) go=course (' Go ', ' 5mons ', 25000) # t1.course=python# s1.course=python# T1.course.tell_course_info () t1.courses.append (python) T1.courses.appEnd (Linux) print (t1.courses) for course_obj in T1.courses:course_obj.info () # T1.tell_course_info () S1.courses.append ( Go) s1.courses.append (python) s1.tell_course_info ()
Packaging

1. What is encapsulation?

Encapsulation is the literal meaning of the hidden, but different from the hidden, encapsulation is external hidden, internal public.

Encapsulate Data properties: Encapsulates the data attributes, and opens up the necessary interfaces for external users. The benefit is the addition of control logic, which controls the operation of the visitor on the attribute and the effect of isolating complexity.

2. How does encapsulation implement hiding?

Preceded by a property name, but not ending with __

Class ATM:    def __insert_card (self):        print (' Insert your card ')    def __transfer (self):        print (' Transfer ')    def __with_draw (self):        print (' Withdraw ')    def __repay (self):        print (' Repay ')    def __check_ Flow (self):        print (' Check your bank flow ')    def run (self):       self.__insert_card ()       Self.__transfer ()       Self.__with_draw ()       self.__repay ()       Self.__check_flow () Obj=atm () Obj.run ()

3. Encapsulate the three points to note:

(1) for an attribute plus __ begins to deform the property name during the attribute definition phase, which is a syntactic variant

(2) This syntactic deformation occurs only once in the definition phase, and the new attributes after the definition are not deformed even if they begin with __

(3) If the parent does not want to override the property quilt class, you can start with the property plus __

Polymorphic

1. What is polymorphism?

Polymorphism is the multiple forms of the same attribute

2. What are the characteristics of polymorphism?

You can directly use the method under the object without regard to the object's specific type

3. What are the benefits of using polymorphism?

(1) Increase the flexibility of the program

(2) Increased scalability of the program

Import ABC  #abstractclass抽象类class Animal (metaclass=abc. Abcmeta): #抽象基类, the abstract base class itself can no longer instantiate    @abc. Abstractmethod    def Eat (self):        pass    @abc. Abstractmethod    def Bark (self):        passclass Cat (Animal):    def Eat (self):        print (' Cat eatting ')    def bark (self):        print ( ' Cat bark ') class Dog (Animal):    def Eat (self):        print (' Dog eatting ')    def bark (self):        print (' Dog Bark ') Dog=dog () Cat=cat () cat.eat () def eat (obj):    Obj.bark () Eat (CAT)

  

Duck type

Python advocates duck type, that is, ' if it looks like, sounds like and walks like a duck, then it's a duck '

Python programmers usually write programs based on this behavior. For example, if you want to write a custom version of an existing object, you can inherit the object

You can also create a new object that looks and behaves like, but has nothing to do with it, which is typically used to preserve the loose coupling of program components.

Object-oriented programming of Python

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.