Python 简明教程

Python - Abstraction

Abstractionobject-oriented programming 中的一个重要原则。它指一种编程方法,通过该方法仅公开对象的相关数据,而隐藏所有其他详细信息。这一方法有助于降低复杂性并提高应用程序开发的效率。

Types of Python Abstraction

有两种类型的抽象。一种是 data abstraction ,其中原始数据通过数据结构隐藏起来,数据结构可以在内部通过隐藏数据实体工作。另一种类型称为 process abstraction 。它指隐藏进程的底层实现细节。

Python Abstract Class

在面向对象编程术语中,如果一个类无法被实例化,即你不能拥有一个抽象类的对象,那么这个类被称为抽象类。但是,你可以把它作为一个基础类或父类来构建其他类。

Create an Abstract Class

若要在 Python 中创建一个抽象类,它必须继承在 ABC 模块中定义的 ABC 类。此模块可在 Python 的标准库中找到。此外,该类必须至少具有一种抽象方法。同样,抽象方法是一种无法调用但可以重写的方法。您需要使用 @abstractmethod 装饰器来装饰它。

Example: Create an Absctract Class

from abc import ABC, abstractmethod
class demo(ABC):
   @abstractmethod
   def method1(self):
      print ("abstract method")
      return
   def method2(self):
      print ("concrete method")

demo 类继承自 ABC 类。有一个 method1(),它是一个抽象方法。注意,该类可具有其他非抽象(具体)方法。

如果你尝试声明一个 demo 类的对象,Python 会引发 TypeError:

   obj = demo()
         ^^^^^^
TypeError: Can't instantiate abstract class demo with abstract method method1

demo 类可以在此处用作另一个类的父类。但子类必须覆盖父类中的抽象方法。否则,Python 会抛出此错误 −

TypeError: Can't instantiate abstract class concreteclass with abstract method method1

Abstract Method Overriding

因此,具有抽象 method overridden 的子类在以下 example 中给出:

Example

from abc import ABC, abstractmethod
class democlass(ABC):
   @abstractmethod
   def method1(self):
      print ("abstract method")
      return
   def method2(self):
      print ("concrete method")

class concreteclass(democlass):
   def method1(self):
      super().method1()
      return

obj = concreteclass()
obj.method1()
obj.method2()

Output

执行此代码时,将生成以下输出 −

abstract method
concrete method