Search code examples
pythoninheritanceabstract

Abstract methods in Python


I am having trouble in using inheritance with Python. While the concept seems too easy for me in Java yet up till now I have been unable to understand in Python which is surprising to me at least.

I have a prototype which follow:

class Shape():
   def __init__(self, shape_name):
       self.shape = shape_name

class Rectangle(Shape):
   def __init__(self, name):
       self.shape = name

In the above code how can I make an abstract method that would need to be implemented for all the subclasses?


Solution

  • Something along these lines, using ABC

    import abc
    
    class Shape(object):
        __metaclass__ = abc.ABCMeta
        
        @abc.abstractmethod
        def method_to_implement(self, input):
            """Method documentation"""
            return
        
    

    Also read this good tutorial: https://pymotw.com/3/abc/

    You can also check out zope.interface which was used prior to introduction of ABC in python.