Abstract base classes

In OOP, abstract base classes are those classes that contain just the method declarations and not their implementations. These classes are not supposed to have independent objects, but rather are built to act as base classes. The classes that derive from the abstract base classes are required to provide implementation for the methods declared in the abstract classes.

In Python, although you can build abstract classes by not providing the implementation for the declared methods, the language in itself does not enforce that concept of derived classes to provide the implementation for the method. So, the following example will run perfectly fine if executed in Python:

class AbstractUser:
def return_data(self):
pass
class User(AbstractUser):
def __init__(self, username):
self.username = username
self.user_data = {}
def return_username(self):
return self.username
aUser = AbstractUser()
user = user('joe')
>>> aUser
<__main__.AbstractUser object at 0x7eff33fe3d68>
>>> user
<__main__.User object at 0x7eff3055b748>

As we can see, the program executed perfectly, even though we did not provide an implementation of the return_data method in the user class.

To work around this problem, Python provides a module called abc, which refers to Abstract Base Class. Let's take a look at how we can use this module to implement abstract base classes in Python:

from abc import ABC, abstractmethod
class AbstractUser(ABC):
@abstractmethod
def return_data(self):
pass

class User(AbstractUser):
def __init__(self, username):
self.username = username
self.user_data = {}
def return_username(self):
return self.username
def return_data(self)
return self.user_data

In this example, the AbstractUser class derives from the abc class, which is the base class for defining the abstract base classes in Python. The @abstractmethod decorator marks a method as abstract and enforces that the derived class should provide an implementation for the method. So, let's take a look at what happens if we try to initialize an object of AbstractUser class:

>>> aUser = AbstractUser()
TypeError: Can't instantiate abstract class AbstractUser with abstract methods return_data

An attempt to do so ends up with Python raising a TypeError.

So, we can see from the preceding example that using the abc module, we can put some enforcement on derived classes to provide an implementation for abstract methods in a class.

The implementation of an abstract base classes provide a template which can be implemented by the child classes while making sure that the child classes must implement the functionality declared inside the base class they are deriving from.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.151