bernie2436
bernie2436

Reputation: 23901

Why is python allowing me to instantiate this class? I am not implementing an abstract method

I am new to abstract classes in Python (v 2.7). I have looked at a few tutorials for abstract classes and it seems like (one) way to implement abstract methods is to import the abc module and use an abstract method decorator, like this.

import abc

class AbstractAlgorithm(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def load(self, input):
        """Retrieve data from the input source and return an object."""
        return

    @abc.abstractmethod
    def save(self, output, data):
        """Save the data object to the output."""
        return


class SpecificAlgorithm(object):

    def load(self, input):
        return input.read()

AbstractAlgorithm.register(SpecificAlgorithm)

I know that python won't let me do this:

AbstractAlgorithm() ==> TypeError: Can't instantiate abstract class AbstractAlgorithm with abstract methods load, save

But why am I able to instantiate a specific version of the abstract class without implementing one of the abstract methods? I would think that this would not be permitted. Am I doing something wrong?

b = SpecificAlgorithm()

Upvotes: 2

Views: 145

Answers (2)

unutbu
unutbu

Reputation: 879749

SpecificAlgorithm must list AbstractAlgorithm as its base class. Otherwise the automated checking mechanism in AbstractAlgorithm's metaclass does not take effect. (More accurately, as Martijn Pieters points out, ABCMeta records abstract methods that have not been overridden in cls.__abstractmethods__. Upon instantiation, object.__new__ raises a TypeError if it finds abstract methods that have not been overridden.)

class SpecificAlgorithm(AbstractAlgorithm):
    ...

b = SpecificAlgorithm()

now yields

TypeError: Can't instantiate abstract class SpecificAlgorithm with abstract methods save

Upvotes: 3

Mike
Mike

Reputation: 413

Python allows you to call parent abstract methods. By having the return line, you have defined a simple implementation of the method. By not creating implementations in the child class, the parent class' implementations are used. This is from the python docs:

Note: Unlike Java abstract methods, these abstract methods may have an implementation. This implementation can be called via the super() mechanism from the class that overrides it. This could be useful as an end-point for a super-call in a framework that uses cooperative multiple-inheritance.

Link: https://docs.python.org/3.4/library/abc.html

Edit: I think unutbu's answer also has something to do with it.

Upvotes: 0

Related Questions