Python Object-oriented programming (II.)

Source: Internet
Author: User

1. Inheritance and derivation

As we have said above, everything in Python is object. We extract the common features and skills from the objects and get the concept of the class. There are also common characteristics between classes and classes, and we can extract common skills and features from classes that have common characteristics and skills, called parent classes.

For example, teachers and students, have a name, age, birthday, gender and so on, will walk, talk, eat ... We can be summed up from the teacher and students a ' person ' class, called the parent class, the teacher and the student is the ' human ' class subclass, the subclass inherits the parent class, has the parent class the characteristic and the method.

Inheritance is a relationship of what ' is ', inheritance is a way of generating new classes, and of course, the purpose is to reduce code reuse.

The basic forms of inheritance are:

class people:     Pass class Student (People):#People is called a base class or parent    Pass

Support multiple inheritance in Python, one subclass can inherit multiple parent classes

We can see all of the inherited parent classes by __bases__ and return a tuple.

class people:     Pass class Animals:     Pass class Student (people,animals):     Pass Print (Student. __bases__) # (<class ' __main__. People ';, <class ' __main__. Animals ' >)print(people.  __bases__)#(<class ' object ';,)

As you can see, in the People parent class, the default also inherits an object class, which is the difference between the new class and the classic class:
Any class that inherits the object class and its subclasses is called a new class, and there is no class that inherits the object class, called the Classic class.

In Python 3, the default is the new class, and in python2.x, the default is the classic class

How does inheritance reduce code? See Example

classpeople:def __init__(self,name,age): Self.name=name Self.age= AgedefWalk (self):Print('%s is Walkig'%self.name)classTeacher (people):def __init__(Self,name,age,level): People.__init__(self,name,age) Self.level=LEVELT1=teacher ('Zhang', 18,10)Print(T1.level)#TenPrint(T1.name)#The Zhang subclass can use the properties defined by the parent classT1.walk ()#Zhang is walking subclasses can use the method of the parent class without definingPrint(Issubclass (Teacher,people))#true to see if the teacher class is a subclass of the people class

As can be seen from the above example, the teacher class inherits the parent class people class, but teacher has its own unique attribute level, the subclass can also define its own unique method, and even the parent class's method can be the same name, but the execution will be defined as the subclass.

This is called derivation.

2. Combination

Inheritance is to solve what ' is ' what is the problem, there is a scene is what has what, such as the teacher has a birthday, the student also has a birthday, the date of the birthday of these attributes, if each class is written, but also duplicate code. But it is not possible for students and teachers to inherit the birthday class. This is where the combination is used . A combination is a problem that solves what ' is '. See Example

classDate:def __init__(self,year,mon,day): Self.year=Year Self.mon=Mon self.day= DaydefTell_birth (self):Print('was born in%s year%s month%s Day'%(self.year,self.mon,self.day))classTeacher:def __init__(self,name,age,year,mon,day): Self.name=name Self.age=Age Self.birth=Date (year,mon,day) T=teacher ('Egon', 19,2010,10,10)Print(T.birth)#<__main__. Date object at 0x0000017e559380f0>T.birth.tell_birth ()#born on October 10, 2010

What the? Too many parameters? *args learned it, you're happy.

1 classDate:2     def __init__(self,year,mon,day):3Self.year= Year4self.mon=Mon5self.day= Day6     defTell_birth (self):7         Print('was born in%s year%s month%s Day'%(self.year,self.mon,self.day))8 9 classTeacher:Ten     def __init__(self,name,age,*args): OneSelf.name=name ASelf.age= Age -Self.birth=date (*args) -T=teacher ('Egon', 19,2010,10,10) the Print(T.birth)#<__main__. Date object at 0x0000017e559380f0> -T.birth.tell_birth ()#born on October 10, 2010
View Code

3. Abstract classes and interfaces

There are two uses of inheritance: 1. Code reuse, subclasses inheriting methods of the parent class

2. Declares that a subclass is compatible with a parent class, defines an interface class interface, defines some interface names (that is, function names) and does not implement interfaces, subclasses inherit the interface class, and implement functions in the interface

It is important to note that there is no interface keyword in Python, we can only mimic the functionality of the interface
For example, in Python, everything is a file, the program is a file, the hardware is a file, text document is also a file, we know what is called a file, is able to read and write, the program, text documents these, should have read and write functions, we can simulate

classInterface:defRead (self):Pass    defWrite (self):Pass        classTxt (Interface):defRead (self):Print('How text documents are read')    defWrite (self):Print('How text documents are written')        classSata (Interface):defRead (self):Print('how hard disk files are read')    defWrite (self):Print('how hard disk files are written')classprocess (Interface):defRead (self):Print('How process data is read')    defWrite (self):Print('How process data is written')
View Code

The point of doing this is that we don't need to know what the subclass has in particular, and since they inherit the file class, they are the files, and they have to read and write these two functions.

The parent class has limited the subclass subclass to have read and write methods, and the name must be the same (of course, now it is only our subjective limitations, we can say that the abstract class, from the code level limit), so that the unification, simulation of the concept of the interface, this is the normalization of the design. in a normalized design, as long as the class is based on an interface design, then all of the objects instantiated by these classes are the same in usage

Let's take another look at abstract classes:

Abstract classes in Python need to be imported into a module for implementation. Abstract classes can only be inherited and cannot be implemented

Abstract class notation:

ImportABCclassFile (metaclass=ABC. Abcmeta): @abc. AbstractmethoddefRead (self):Pass@abc. AbstractmethoddefWrite (self):Pass#The parent class uses an abstract class, and the subclass must inherit the method of the parent class, and the name must be the same#This enables code-level restrictionsclassTxt (File):defRead (self):Print('How text documents are read')    defWrite (self):Print('How text documents are written')

4. The implementation principle of inheritance

1) Inheritance Order:

Python supports multiple inheritance, what is the order of inheritance when a class inherits multiple parent classes? This order is not the same in the new class and the classic class.

In the new class, the inheritance order is breadth-first, in the classic class is depth first, and a chestnut:

Figure doesn't matter, look at the content
In this diagram, H is a subclass, H inherits E,f,g,e,f,g, inherits B,c,d,b,c,d, and inherits a

The order in the new class is: H E B F C G D A

The order in the classic class is: H E B A F C G D

2) Principle of succession:

When we define a class, Python resolves an inheritance order list (MRO list) based on the above inheritance rules, which can be viewed through MRO (), but this method is only available in the new class, and the classic class does not

Mro

3) Super () method

How did we use inheritance before?

class Parent (object):     def __init__ (self,name,age):        self.name=name        self.age=AgeClass child ( Parent):    def__init__(self,name,age,salary):        parent. __init__ (self,name,age,salary)        self.salary=salary

This is actually the same as the inheritance of the wording, if the parent class name changed, in the subclass also to change, more elegant style is to use super ()

class Parent (object):     def __init__ (self,name,age):        self.name=name        self.age=AgeClass child ( Parent):    def__init__(self,name,age,salary):        super (). __init__ (name,age)        self.salary=salary

This is the notation in Python3, if it is written in parentheses after Python2,super (child,self)

Note:the Super () method applies only to modern classes

If it is a multi-inheritance relationship, use the MRO list, if it is to inherit multiple parent class methods, it is still a good way to use the previous names of the method reference

Python Object-oriented programming (II.)

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.