python- abstract class

Abstract class

Interface : Interface refers to himself available to users to call their own way function \ method \ entry

Interface to extract a group of class a common function, we can put an interface as a function of the set, and then let the child class to implement the function interface.

This is the normalization , normalization is as long as the class is implemented based on the same interface , the object of all of these classes generated during use, from the use of it all the same

Abstract class: abstract class is a special class, it special is that can only be inherited, can not be instantiated

If the content class is extracted from the same subject from the pile, the abstract class is extracted from the pile of the same content class, including properties characteristic properties and methods

From the implementation point of view, the general category of the abstract class except that: the abstract method of the abstract class only (not realize the function) , the class can not be instantiated, can be inherited, and subclasses must implement the abstract methods . This point is somewhat similar to the interface, but in fact are different

An abstract class in Py, the required guide module abc

Defines an abstract class:

import abc #利用abc模块实现抽象类
class obj_name(metaclass = abc.ABCMeta):
    @abc.abstractmethod
    def func(self):
        pass

Examples of presentations:

#一切皆文件
import abc #利用abc模块实现抽象类

class All_file(metaclass=abc.ABCMeta):
    all_type='file'
    @abc.abstractmethod #定义抽象方法,无需实现功能
    def read(self):
        '子类必须定义读功能'
        pass

    @abc.abstractmethod #定义抽象方法,无需实现功能
    def write(self):
        '子类必须定义写功能'
        pass

# class Txt(All_file):
#     pass
#
# t1=Txt() #报错,子类没有定义抽象方法

class Txt(All_file): #子类继承抽象类,但是必须定义read和write方法
    def read(self):
        print('文本数据的读取方法')

    def write(self):
        print('文本数据的读取方法')

class Sata(All_file): #子类继承抽象类,但是必须定义read和write方法
    def read(self):
        print('硬盘数据的读取方法')

    def write(self):
        print('硬盘数据的读取方法')

class Process(All_file): #子类继承抽象类,但是必须定义read和write方法
    def read(self):
        print('进程数据的读取方法')

    def write(self):
        print('进程数据的读取方法')

wenbenwenjian=Txt()
yingpanwenjian=Sata()
jinchengwenjian=Process()

#这样大家都是被归一化了,也就是一切皆文件的思想
wenbenwenjian.read()
yingpanwenjian.write()
jinchengwenjian.read()
  • Essence is the abstract class, referring to the similarity of a set of classes, including the feature attributes (e.g. all_type) methods and attributes (e.g., read)
  • Interface only emphasized the similarity of method attributes.
  • An abstract class is a concept interposed between a class and interface, along with some features classes and interfaces can be used to achieve normalization Design

Guess you like

Origin www.cnblogs.com/liuxu2019/p/12115908.html