Skip to main content
 首页 » 编程设计

python之Python 中的抽象

2025年05月04日7xing901022

我正在尝试为一个项目选择 Python,但我对如何使用抽象和类有点困惑。 (我不是一个非常有经验的程序员,所以对这个问题的基本水平表示歉意。)我来自 Java/Ocaml 背景,我一直在尝试做的如下:我有一个图的抽象类和一个 graphadvanced(一个带有一些更花哨的方法的图),看起来像这样

class AbstractGraph:  
   def method1(self):  
      raise NotImplementedError 
   ... 
 
class AbstractAdvanced: 
   def method2(self): 
      raise NotImplementedError  
   ...  

然后我有一个图的实现:

class Graph(AbstractGraph): 
   def method1(self): 
      * actual code *  

现在我的问题是:我可以做这样的事情吗?

class Advanced(AbstractAdvanced, AbstractGraph): 
   def method2(self): 
      *actual code, using the methods from AbstractGraph* 

换句话说,我如何根据 AbstractGraph 的方法抽象地定义 Advanced 的方法,然后以某种方式将 Graph 传递给构造函数以获得 Advanced 的实例,该实例使用 Advanced 的定义和 Graph 的实现?

就 Ocaml 而言,我试图将 AbstractAdvanced 和 AbstractGraph 视为模块类型,但我已经尝试了一些 python,但我不确定如何让它工作。

请您参考如下方法:

如果你想创建抽象基类,你可以,但它们的用途有限。以具体类开始您的类层次结构(在继承自对象或其他第三方类之后)更为正常。

如果你想创建一个类,将各种类拼凑在一起,部分协议(protocol),那么只需继承你的实现类:

#Always inherit from object, or some subtype thereof, unless you want your code to behave differently in python 2 and python 3 
 
class AbstractGraph(object):  
   def method1(self):  
      raise NotImplementedError 
 
class Graph(AbstractGraph): 
   def method1(self): 
      * actual code *  
 
class GraphToo(AbstractGraph): 
   def method1(self): 
      * actual code *  
 
class AbstractAdvanced(AbstractGraph): 
   def method2(self): 
      raise NotImplementedError  
 
class Advanced(Graph,AbstractAdvanced): 
   def method2(self): 
      *actual code, using the methods from Graph* 
 
# order of classes in the inheritance list matters - it will affect the method resolution order 
class AdvancedToo(GraphToo, Advanced): pass