Python-based inheritance derivation, composition, interface, and abstract classes

Source: Internet
Author: User

Inheritance and derivation of classes

Classic class and New class

In Python3, all classes inherit object by default, but all subclasses that inherit the object class, and subclasses of that subclass, are called modern classes (all classes in Python3 are modern classes)

Subclasses that do not inherit the object class become the classic class (in Python2, a class that does not inherit object, and its subclasses, are classic classes)

1 class People:2     PASS3 class Animal:4     pass5 class Student (people,animal): #People, Animal is called a base class or parent class, Student is a subclass, Student inherits all the properties of people and animal 6     PASS7 Print (student.__bases__)    #__bases__方法, viewing the tuple of inherited classes 8 print (people.__ BASES__) 9 Print (animal.__bases__)

Output Result:

1 (<class ' __main__. People ';, <class ' __main__. Animal ' >)    #继承了两个父类2 (<class ' object ')    #默认继承了object类3 (<class ' object ');

Inherited

Inheritance is to reduce the problem of code reuse to reduce code redundancy.

Inheritance is a relationship of what is what, such as teacher class is human, and not teacher class is birthday class

Examples of inheriting classes:

1 class people:    #定义父类People 2     def __init__ (self, Name, age): 3         self.name = name 4         self.age = Age 5     def Walk (self): 6         print ('%s is walking '%self.name) 7  8 #Teacher类和Student类无任何属性 9 class Teacher (People):    # Teacher class inherits properties of people class     Pass11 class Student (people):    #Student类继承People类的属性12     Pass

Reference test:

1 T=teacher (' Bob ')    #实例化一个Teacher对象, not people object, student subclass 2 print (type (t))  3 print (T.name,t.age) 4 Print (t.__dict__) 5 t.walk ()    #Teacher子类继承了People的属性 so that an object of the teacher subclass can be called to the parent class's properties 6  7 output Result: 8 <class ' __main_ _. Teacher ' > 9 bob 1810 {' name ': ' Bob ', ' age ': 18}11 Bob is walking

Derived

Derivation is based on inheriting the parent class of subclasses, defining attributes that are unique to subclasses, such as teacher can have the division of teacher level, have the division of Teaching course, but inherit the parent class people class is no hierarchy and the division of the course.

Example:

 1 #定义父类People 2 class People:3 def __init__ (self, Name, Age,sex): 4 self.name = name 5 Self.age = AG         E 6 Self.sex=sex 7 def Walk (self): 8 print ('%s are walking '% self.name) 9 def test (self): 10     Print (' Test class from Father class%s '%self.name) #定义Teacher子类12 class Teacher (people): School = ' Jialidun ' 14 def __init__ (self, Name, age,sex,level,salary): people.__init__ (Self,name,age,sex) #继承父类的初始化内容, parameters received when instantiating Name, age, and sex are passed to people.__init__16 self.level=level #派生的独有属性17 self.salary=salary #派生的独有属性18 def t Each: the #派生的独有属性19 print ('%s is teaching '%self.name)-def test (self): #派生父类的已有属性, the object takes precedence when making property references Class used in instantiation people.test (self) print (' from teacher ') #定义Student子类24 class Student (People): def _ _init__ (self, Name, Age,sex,group): people.__init__ (self, name, age, Sex) self.group=group28 def s           Tudy (self): 29  Print ('%s is studying '%self.name) 

Test validation:

1 t=teacher (' Natasha ', ' Male ', 10,3000) #__init__ (t, ' Natasha ', 3, ' Male ', 10,3000) 2 print (teacher.__bases__ (teacher.__dict__) 4 t.test ()

Combination

Unlike inheritance, a combination is an inclusive meaning that represents a relationship of what is and is also intended to reduce duplication of code

Example: Or people, teacher, and student, just add a birthday birthday class

 1 #Birthday类, need to pass date 2 class Birthday:3 def __init__ (self,year,mon,day): 4 self.year=year 5 Self.mon =mon 6 Self.day=day 7 def Tell_birth (self): 8 print (' Born <%s> year <%s> month <%s> Day '% (self.y Ear,self.mon,self.day) 9 #People类, need to accept the name of the age and Month day, month day passed to birthday class People:11 def __init__ (self, name, ages, year, MO N, day): Self.name = name13 self.age = Age14 #__init__接收的year, Mon, day passed to birthday class Sel F.birth = Birthday (year, Mon, day) #包含Birthday类, birthdays are not just human, other animals can also have birthdays, unlike inheriting from Def Walk (self): + print ('%s is Walking '% self.name) #Teacher类19 class Teacher (People): Def __init__ (self, name, age, year, Mon, day,level,salary         ): #__init__接收的name, age, year, Mon, day passed to People people.__init__ (Self,name,age,year,mon,day) 23 Self.level=level24 self.salary=salary25 def teach (self): + print ('%s is teaching '%self.name) #Stu Dent Class Student (PeOple): Def __init__ (self, name, age, year, Mon, Day,group): people.__init__ (Self,name,age,year,mon,day) 31 SELF.GROUP=GROUP32 def study (self): "Print ('%s is studying '%self.name)

Test validation:

1 t=teacher (' Hurry ', 18,1990,2,33,10,3000)    #传入的值为Teacher类接收的值2 print (t.name,t.age)    #对象t的名字和年龄3 print ( T.birth)    #输出的是一个类对象, because the birth property defined by the parent class people is a class Birthday4 T.birth.tell_birth ()    #查看对象t所继承的People类的birth属性 ( Birthday Class) Tell_birth () attribute 5 print (t.birth.year) 6 print (T.birth.mon) 7 print (T.birth.day)

Interfaces and abstract classes

Interface

Interface is a set of functions, to invoke a set of functions, you need to make calls through the interface, and do not need to focus on how this set of functions are implemented, only the result.

In a class, an interface is an extract of a group of common functions, which can be used as a collection of functions.

Examples of Python emulation interfaces:

1 #模仿Linux内文件读写的接口, Linux Whether it is text, disk or process is implemented through files, but the method is different, but it does not matter 2 class File:    #定义一个接口类, provides the read and write methods, But it must be pass no processing process, because the implementation of the function depends on the subclass 3     def read: #定接口函数read 4         pass 5     def write (self): #定义接口函数write 6         Pass 7 #定义子类实现读写功能 8 #文本文件的读写 9 class Txt (File): #文本, specifically implemented Read and Write10     def du (self):     #注意并不是read11         print (' Text data reading method ')     def Xie (self):    #注意并不是write13         Print (' Write method of text data ') #硬盘数据的读写15 class Sata (File): #磁盘, Implementation of Read and WRITE16     def read (self):         print (' Read method of hard drive data ') "     def Write" ("         write method for hard disk data") ) #进程数据的读写21 class Process (File): def read (self)     :         print (' Read method of process data ')     def write (self): 25         print (' Write method for process data ')

Test verification: Hard disk and process, so the production of text and hard disk test can be

HDD read/write Test:

1 disk=sata ()    #实例化一个硬盘读写对象2 disk.read ()    #硬盘读3 disk.write ()    #硬盘写4 5 Output: 6 Read method of hard disk data 7 How to write hard disk data

Text Read and write test: After execution will find no output, it is because the TXT object actually accesses the read and write property is not a subclass of the properties provided by TXT, TXT provides the property is Du and Xie, but the TXT object has read and write properties, Don't forget that the TXT class inherits the properties of the parent class file, so the read and write properties of the TXT object are actually provided by the parent class file.

1 Txt=txt () 2 Txt.read () 3 txt.write ()

The correct approach is to change the txt class Du and Xie methods to the read and write methods, so the meaning of this is normalized

Normalization, so that users do not have to care about the object's class, only need to know that these objects have certain functions, which greatly reduces the user's use of difficulty.

Abstract class

Abstract classes are essentially classes, but abstract classes can only be inherited and cannot be instantiated, that is, they can be parent classes, but cannot generate objects.

The abstract class is between the interface and normalization, and is used to realize the normalization of the interface.

When a subclass inherits an abstract class, if an abstract class defines an abstract method, the subclass must define a method with the same name. That is, the parent class limit:

1. Subclasses must have a method of the parent class

2. Subclasses must implement methods that are the same as the names of the methods of the parent class

Python's abstract class is implemented through the ABC module.

An example of an interface normalization:

1 Import ABC 2 class File (METACLASS=ABC. Abcmeta):  #metaclass指的是元类, the side will speak, now just remember the word 3     @abc. Abstractmethod     #抽象方法, that is, an adorner decoration Read Property 4     def read ( Self): 5         Pass 6     @abc. Abstractmethod      #抽象方法, i.e. an adorner decoration write property 7     def write (self): 8         pass 9 # # Error Typeerror:can ' t instantiate abstract class TXT with abstract methods read, Write10 # CLA When inheriting the file class without the read and write methods SS Txt (File): One #     def du (self): #         Print (' Read method of text data ') #     def Xie (self): #         Print (' Write method for Text data ') 15 #定义子类具体实现文本的读写操作16 class Txt (File):     def read (self):         print (' Read method of text data ')     def write (self): 20         print (' Writing method of text data ') #定义子类具体实现硬盘的读写操作22 class Sata (File):     def read (self):         print (' Read method of hard drive data ') 25     def write (self):         print (' Write method of hard disk data ') #定义子类具体实现进程的读写操作28 class Process (File):     def read (self): 30         print (' Read method of process data ')     def write (self):         print (' Write method of process data ')

Test validation:

1 T=txt () 2 T.read () 3 T.write () 4 s=sata () 5 s.read () 6 s.write () 7 Output Result: 8 Text data Read method 9 Text data write method 10 hard Drive data Read method 11 hard disk data write method

Python-based inheritance derivation, composition, interface, and abstract classes

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.