Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I am a little bit unclear about how to use abstraction and classes. I have abstract classes for a graph and a graph advanced, that looks 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 main problem is: can I do something like this?

class Advanced(AbstractAdvanced, AbstractGraph):

   def method2(self):

      *actual code, using the methods from AbstractGraph*

1 Answer

0 votes
by (108k points)

Please be informed that you can create abstract base classes, however, they are of confined utility. It's more common to start your class hierarchy with particular 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

Kindly refer to the Python tutorial for more information regrading classes and objects.  

Related questions

0 votes
1 answer
asked Dec 23, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Mar 11, 2020 in Java by Sudhir_1997 (55.6k points)
0 votes
1 answer
asked Mar 2, 2021 in Java by rahulnayar01123 (6.1k points)

Browse Categories

...