Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in Python, requiring certain methods to be defined in subclasses

In Java, for example, you can make a class MyClass with certain methods that are specified but not implemented in MyClass, but must be implemented in any class MySubClass that inherits from MyClass. So basically there is some common functionality among all subclasses you want, so you put it in MyClass, and there is some functionality unique (but required) for each subclass, so you want it in each subclass. How can this behavior be achieved in Python?

(I know there are concise terms to describe what I'm asking, so feel free to let me know what these are and how I can better describe my question.)

like image 871
tscizzle Avatar asked Feb 05 '26 00:02

tscizzle


2 Answers

A very basic example but the abc docs provide a few more

import abc

class Foo():
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def bar(self):
        raise NotImplemented

class FooBar(Foo):
    pass

f = FooBar()
TypeError: Can't instantiate abstract class FooBar with abstract methods bar

Edit: In Python3 the syntax is slightly different:

import abc

class Foo(object, metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def bar(self):
        raise NotImplementedError

class FooBar(Foo):
    pass

f = FooBar()
like image 75
Padraic Cunningham Avatar answered Feb 07 '26 15:02

Padraic Cunningham


You can't require the implementation of a method in a subclass in a way that will break at compile-time, but the convention on writing a method on the base class that must be implemented in the subclasses is to raise NotImplementedError.

Something like this:

class MyBase(object):
    def my_method(self, *args, **kwargs):
        raise NotImplementedError("You should implement this method on a subclass of MyBase")

Then your subclasses can implement my_method, but this will break only when the method is called. If you have comprehensive unit tests, as you should, this won't be a problem.

like image 45
Pedro Werneck Avatar answered Feb 07 '26 14:02

Pedro Werneck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!