Search code examples
pythonabc

Python: enforcing abstract method


I have written the follow code to demonstrate abstract methods that must be implemented by its subclasses. I read that when a method in a parent class is decorated as abstract, its subclass must implement it otherwise it cannot be instantiated. However, in the following code, the 'Slug' subclass does not implement the abstract method, yet it can still instantiate without errors being thrown. I thought in this case Python will complain?

Have I misunderstood something?

Thanks

import abc

class Animal(object):

    __metaclass__ = abc.ABCMeta

    def __init__(self, species):
        self._species=species

    def get_species(self):
        return self._species

    @abc.abstractmethod
    def eat(self):
        pass

class Slug(Animal):

    def __init(self, species):
        super(species)

    def run(self):
        print("running")

    # def eat(self):
    #     pass


sl = Slug("slug")
print(sl.get_species())

Solution

  • no, you understood perfectly well! it is just that the python 3 syntax for abc.ABCMeta is:

    class Animal(metaclass=abc.ABCMeta):
        ...
    

    instead of __metaclass__ = abc.ABCMeta which was used in python 2. alternatively you can just inherit from ABC: class Animal(abc.ABC):. see doc.

    and then:

    class Slug(Animal):
    
        def __init(self, species):
            super.__init__(species)
    
        ...
    

    this will result in

    Traceback (most recent call last):
      File "/home/.../...py", line 33, in <module>
        sl = Slug("slug")
    TypeError: Can't instantiate abstract class Slug with abstract methods eat