Abstraction in Python?

Topics about the Software of Revolution Pi
Post Reply
User avatar
MukeshPython
Posts: 1
Joined: 22 Jun 2022, 13:29
Answers: 0

Abstraction in Python?

Post by MukeshPython »

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 graph advanced (a graph with some more fancy methods), that looks something like this

Code: Select all

class AbstractGraph: 
   def method1(self): 
      raise NotImplementedError
   ...
 
class AbstractAdvanced:
   def method2(self):
      raise NotImplementedError 
   ... 
I then have an implementation of a graph:

Code: Select all

class Graph(AbstractGraph):
   def method1(self):
      * actual code * 
Now my question is: can I do something like this?

Code: Select all

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.
kjkoster
Posts: 87
Joined: 12 Feb 2022, 10:42
Answers: 2

Re: Abstraction in Python?

Post by kjkoster »

Dear MukeshPython,

In general I would advise not to try to keep your Java programming style in Python. They have different philosophies at their cores and if you try to write Java in Python too much you actually make your life harder for yourself.

That said: this tutorial will probably answer your question better than I can: https://realpython.com/inheritance-composition-python/ Hope this helps.

Kees Jan (who also learned Python after Java)
Post Reply