Home > Software design >  (Python) Compelling a class to implement particular methods
(Python) Compelling a class to implement particular methods

Time:09-22

I know the inheritance in class. Every methods which a superclass has is inherited to its subclass. So unless needed particularly, the subclass doesn't have to implement the inherited methods again.

But I want to make sure a subclass to re-implement all the methods which a superclass has. The point is that all classes in the same group(such as classes inherit the same superclass) have to implement the same methods individually. The classes need some structure that designate what methods have to be implemented.

What am I supposed to do?

CodePudding user response:

In object oriented programming, this is achieved through the use of an interface. You'd have to import the python interface module, then have your class inherit from this module. Here is a guide with some practical examples: https://www.geeksforgeeks.org/python-interface-module/#:~:text=In python, interface is defined using python class,interfaces are implemented using implementer decorator on class.

CodePudding user response:

In C you would be looking to make pure virtual methods on your base class, prompting a compile-time error on a subclass not implementing the method, this is typically the way interfaces are defined.

Python provides the abstractmethod decorator (see here: https://docs.python.org/3/library/abc.html#abc.abstractmethod) for similar ends. Unlike C you will be able to run your program with subclasses which haven't implemented the base class abstractmethod, but the subclass will throw a TypeError exception at instantiation.

There's an example here: https://stackoverflow.com/a/26458670/5932855

CodePudding user response:

Use abstract base classes in Python. Create a class definition that extends (subclasses) from ABC. This is an abstract class, similar to interfaces in other languages such as Java for example, which additionally can implement concrete methods if so desired. To create a stub method, mark it as @abstractmethod (or a similar decorator for class and static methods) and add a comment block; no method definition is necessary. To create a concrete method, simply add logic under the method as you normally would to any class. Then you can have your concrete subclasses extend from this abstract class, and the interpreter will by default require you to implement all declared abstract methods.

  • Related