Object-oriented (interfaces and abstract classes) of Python

Source: Internet
Author: User

First, the interface

What is an interface

There are two uses of inheritance:

1: Inherit the method of the base class and make your own changes or extensions (code reuse).

2: Declares that a subclass is compatible with a base 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.

classFile:#defines the interface file class to mimic the concept of an interface.     defRead (self):#Fixed interface function Read        Pass    defWrite (self):#defining an interface function write        PassclassTXT (File):#text that implements read and write specifically    defRead (self):Print('How to read text data')    defWrite (self):Print('How to read text data')classSata (file):#disk, specifically implemented read and write    defRead (self):Print('How to read hard disk data')    defWrite (self):Print('How to read hard disk data')classProcess (File):defRead (self):Print('method of reading process data')    defWrite (self):Print('method of reading process data')
#parent class to restrict#1: Subclasses must have a method of the parent class#2: Subclasses must implement a method that is the same as the name of the parent class's methodImportABCclassFile (metaclass=ABC. Abcmeta): @abc. AbstractmethoddefRead (self):Pass@abc. AbstractmethoddefWrite (self):PassclassTXT (File):#text that implements read and write specifically    defRead (self):Pass    defWrite (self):PassT=txt ()

In practice, the first meaning of inheritance is not very significant, and often harmful. Because it causes the subclass to be strongly coupled to the base class.

The second meaning of inheritance is very important. It is also called "Interface inheritance."
Interface inheritance is essentially a requirement "to make a good abstraction, which prescribes a compatible interface so that the external caller does not have to care about the specifics, and treats all the objects of a particular interface in a non-discriminatory process"--this is called Normalization in program design.

Normalization allows high-level external users to handle the collection of objects that are compatible with all interfaces without distinction-just like the generic file concept of Linux, everything can be treated as a file, regardless of whether it is memory, disk, network, or screen (of course, for the underlying designer, it can also distinguish between "character devices" and " And then make a specific design: to what extent, depending on the requirements.

Second, abstract class

1. What is abstract class

An abstract class is a special class that is unique in that it can only be inherited and cannot be instantiated.

2, why should have abstract class

If a class extracts the same content from a bunch of objects , the abstract class extracts the same content from a bunch of classes , including data properties and function properties.

For example, we have banana class, Apple class, Peach class, from these classes to extract the same content is the abstract fruit of the class, you eat fruit, either to eat a specific banana, or to eat a specific peach ... You can never eat something called a fruit.

From a design perspective, if a class is abstracted from a real object, the abstract class is based on class abstraction.

From an implementation perspective, abstract classes differ from ordinary classes in that abstract classes can only have abstract methods (without implementing functionality), that classes cannot be instantiated, can only be inherited, and subclasses must implement abstract methods. This is a bit similar to the interface, but it's actually different.

3. Implement abstract classes in Python
1ImportABC2classFile (METACLASS=ABC. Abcmeta):#Metaclass refers to the meta-class, the side will say, now just remember the word3 @abc. Abstractmethod#abstract method, that is, an adorner decorates the Read property4defRead (self):5Pass6 @abc. Abstractmethod#abstract method, that is, an adorner decorates the Write property7defWrite (self):8Pass9## When inheriting the file class, if there is no read and write method, the error Typeerror:can ' t instantiate abstract class TXT with abstract methods read, write< /c1>10#class Txt (File):11#def du (self):12#print (' Read method of text data ')13#def Xie (self):14#print (' Write method for Text data ')15#define subclasses to implement read and write operations on text16classTxt (File):17defRead (self):18Print('How to read text data')19defWrite (self):20Print('How to write text data')21st#define subclasses to implement read and write operation of hard disk22classSata (File):23defRead (self):24Print('How to read hard disk data')25defWrite (self):26Print('How to write hard disk data')27#define subclasses to implement read and write operations of the process28classProcess (File):29defRead (self):30Print('method of reading process data')31defWrite (self):32Print('How process data is written')

Test validation:

1 t=234 s=56789 Writing method for text data  How to read hard disk data 11 How to write hard disk data

III. application and serialization of combinations

1. Combination application of Date class, course class, human, teacher class, student class
classDate:#Defining Date Classes    def __init__(self,name,year,mon,day): Self.name=name Self.year=Year Self.mon=Mon self.day= DaydefTell_birth (self):Print('%s%s-%s-%s'%(self.name,self.year,self.mon,self.day))classCourse:#Defining Account Classes    def __init__(self, name, price, period): Self.name=name Self.price=Price Self.period=perioddefTell_course (self):Print(" "----------%s Info----------Course name:%scourse price:%scourse period:%s" "%(Self.name, Self.name, Self.price, self.period))classPerson:#Define Human    def __init__(self,name,age,sex): Self.name=name Self.age=Age Self.sex=Sex self.courses=[]    defWalk (self):Print('%s is walking'%self.name)defTell_course (self): forObjinchSelf.courses:obj.tell_course ()classTeacher (person):#define teacher class, inherit person    def __init__(self,name,age,sex,salary,level): person.__init__(self,name,age,sex) self.salary=Salary Self.level= LeveldefTeach (self):Print('%s is teaching'%self.name)defTell_info (self):Print(" "----------%s Info---------name:%s Age:%s SEX:%s SAL:%s level:%s" "%(self.name,self.name,self.age,self.sex,self.salary,self.level))classStudent (person):#define student class, Inherit person    def __init__(self,name,age,sex,group): person.__init__(self,name,age,sex) Self.group=GroupdefStudy (self):Print('%s is teaching'%self.name)defTell_info (self):Print(" "----------%s Info---------name:%s Age:%s SEX:%s GROUP:%s" "%(Self.name,self.name,self.age,self.sex,self.group)) Egon=teacher ('Egon', 18,'male', 3000,10) Python=course ('Python', 15800,'6mons') Linux=course ('Linux', 1800,'3mons') egon.courses.append (python) egon.courses.append (Linux) egon.tell_course () Egon.birth=date ('Egon', 1991,11,11) Egon.birth.tell_birth () XH=student ('XH', 18,'male','group1') xh.courses.append (python) xh.tell_course () Xh.tell_info ()

2. Serialization

classStudent:def __init__(self, name, age, Sex, group): Self.name=name Self.age=Age Self.sex=Sex Self.group=GroupdefStudy (self):Print('%s is study'%self.name)defTell_info (self):Print(" "----------%s Info---------name:%s age:%s sex:%s group:%s" "%(self.name,self.name,self.age,self.sex,self.group))ImportPICKLEXH=student ('XH', 18,'male','group1') with open ('STUDENTDB.PKL','WB') as F:pickle.dump (xh,f) with open ('STUDENTDB.PKL','RB') as F:obj=pickle.load (f) obj.tell_info ()

Object-oriented (interfaces and abstract classes) 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.