Python中的抽象?

2024-10-01 19:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个项目学习Python,但我对如何使用抽象和类有点困惑。(我不是一个很有经验的程序员,所以对这个问题的基本层次表示歉意。)我来自Java/Ocaml背景,我一直试图做的是:我有一个图形的抽象类和一个graphadvanced(一个带有一些更奇特方法的图),看起来像这样

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

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

然后我有一个图形的实现:

^{pr2}$

现在我的问题是:我能做这样的事吗?在

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

换言之,我如何用AbstractGraph的方法抽象地定义Advanced的方法,然后以某种方式将Graph传递给一个构造函数,从而得到一个使用Advanced定义和Graph实现的Advanced实例?在

就Ocaml而言,我试图将AbstractAdvanced和AbstractGraph视为模块类型,但我对python做了一些尝试,我不确定如何实现这一点。在


Tags: 项目方法self图形定义defclassadvanced
1条回答
网友
1楼 · 发布于 2024-10-01 19:21:40

如果你想创建抽象基类,你可以,但它们的效用有限。用具体的类来启动你的类层次结构(从对象或其他第三方类继承之后)是比较正常的。在

如果要创建一个类,将部分协议的各种类组合在一起,则只需从实现类继承:

#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

相关问题 更多 >

    热门问题