Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Classes with the same methods, but defined differently

I am creating a collection of classes which all have the same 4 methods only: __init__, tick, kill, and complete. The methods are defined differently in every class, however. It seems like it would nonetheless make sense to have all the classes inherit from a general class, in which these functions are not actually defined but their existence is guaranteed, so to speak. Is this good practice, and if so, what’s the best way to go about it?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You’re looking for the idea of the abstract class: it defines the interface for classes that inherit from it, but doesn’t specify anything about the implementation:

from abc import ABC, abstractmethod


class MyABC(ABC):
    @abstractmethod
    def tick(self):
        ...


class MyRealClass1(MyABC):
    def tick(self):
        print("tick1")


class MyRealClass2(MyABC):
    def tick(self):
        print("tick2")


one = MyRealClass1()
two = MyRealClass2()

one.tick()
two.tick()

Both classes inherit from MyABC, but you cannot instance MyABC, it’s only there to serve as template to base other classes on.

If you try to make a class that inherits from it, but you don’t implement tick():

class MyRealClass3(MyABC):
    def foo(self):
        print("foo")


three = MyRealClass3()

Your editor, IDE, or linter will complain that you need to implement tick() on the class definition, and if you instance the class like here, there will be an error:

TypeError: Can't instantiate abstract class MyRealClass3 with abstract method tick
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading