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?

8/23/2019 12:32:05 PM

Accepted Answer

Something along these lines, using ABC

import abc

class Shape(object):
    __metaclass__ = abc.ABCMeta

    def method_to_implement(self, input):
        """Method documentation"""

Also read this good tutorial: http://www.doughellmann.com/PyMOTW/abc/

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

12/8/2010 12:32:00 AM

Before abc was introduced you would see this frequently.

class Base(object):
    def go(self):
        raise NotImplementedError("Please Implement this method")

class Specialized(Base):
    def go(self):
        print "Consider me implemented"

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow