I'm trying to pick up Python for a project, and I'm a bit confused about how to use abstraction and classes. (I'm not a very experienced programmer, so apologies for the basic level of this question.) I come from a Java/Ocaml background, and what I've been trying to do is as follows: I have abstract classes for a graph and a graphadvanced (a graph with some more fancy methods), that look something like this
class AbstractGraph:
def method1(self):
raise NotImplementedError
...
class AbstractAdvanced:
def method2(self):
raise NotImplementedError
...
I then have an implementation of a graph:
class Graph(AbstractGraph):
def method1(self):
* actual code *
Now my question is: can I do something like this?
class Advanced(AbstractAdvanced, AbstractGraph):
def method2(self):
*actual code, using the methods from AbstractGraph*
In other words, how can I define the methods of Advanced abstractly in terms of the methods of AbstractGraph, and then somehow pass Graph into a constructor to get an instance of Advanced that uses Advanced's definitions with Graph's implementation?
In terms of Ocaml, I'm trying to treat AbstractAdvanced and AbstractGraph as module types, but I've played around a little with python and I'm not sure how to get this to work.
1 Answer 1
If you want to create abstract base classes, you can, but they are of limited utility. It's more normal to start your class hierarchy (after inheriting from object, or some other third-party class) with concrete classes.
If you want to create a class that pieces together various classes that partially some protocol, then just inherit from your implementing classes:
#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
9 Comments
Graph class would get all those methods for you.ConcreteAdvanced class to hold your method2 implementation, then inherit from both ConcreteAdvanced and whichever of your graph classes. Thus, there would be no code duplication.
codetab when you're editing