## Example: Create a abstract class and inherit it
# import the 'ABC' class and 'abstractmethod' function from 'abc' module
from abc import ABC, abstractmethod
# inherit the 'ABC' class to create a abstract class
class MyBase(ABC):
# define abstract methods by using 'abstractmethod' as decorator
@abstractmethod
def get_vars():
pass
@abstractmethod
def change_values(self, a, b):
pass
# defining combination of method types
# Notice: 'abstractmethod' should always follow later
@staticmethod
@abstractmethod
def some_info():
print("this method is both static and abstract")
def mydefault_fun():
print("This is normal method")
# Create concrete classes using 'MyBase' as parent class
class MyConcrete1(MyBase):
def __init__(self, a, b):
self.a = a
self.b = b
def change_values(self, a, b):
self.a = a
self.b = b
def get_vars(self):
return self.a, self.b
def some_info(self):
print(f"This is MyConcrete1")
# Creating another concrete class
class MyConcrete2(MyBase):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def get_vars(self):
return self.a, self.b, self.c
# Creating a instance of concrete classes
my_concrete1 = MyConcrete1(10, 20)
print(my_concrete1.get_vars()) # (10, 20)
my_concrete1.some_info() # This is MyConcrete1
## Remember a concrete class has to implement all abstract methods
# of the abstract class, also note that 'mydefault_fun()' is not a
# method abstract, so it is not required to be defined, 'MyConcrete2'
# will raise 'TypeError' due to not implementing all abstract methods,
my_concrete2 = MyConcrete2(10, 20, 30) # TypeError: Can't instantiate \
# abstract class MyConcrete2 ...
# You cannot instantiate a abstract class
my_base = MyBase() # TypeError: Can't instantiate abstract class MyBase ...