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 :
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