"Немцы учат русский язык". Был молодой, мечтал попасть на такое шоу, сейчас 45 мечтаю еще больше!!!.

Alexandr

Hatched by Alexandr

Mar 28, 2024

4 min read

0

"Немцы учат русский язык". Был молодой, мечтал попасть на такое шоу, сейчас 45 мечтаю еще больше!!!.

"Beginner's guide to abstract base class in Python". Skip to content Log in Create account 12 Add reaction 7 Jump to Comments 14 Save Dollar Dhingra Posted on 2 апр. 2021 г. • Updated on 1 июн. 2021 г. • Originally published at dollardhingra.com 9 3 Beginner's guide to abstract base class in Python python oop programming What is an abstract base class? In simple words, an abstract base class provides a blueprint for other classes. Abstract base classes don't contain the implementation. Instead, they provide an interface and make sure that the derived classes are properly implemented.

Abstract base classes provide a way to define common methods and properties that should be implemented by the derived classes. This concept is similar to how a blueprint provides a guide for constructing a building. In the context of programming, abstract base classes act as a foundation for other classes, ensuring that they follow a certain structure.

Let's take the example of a game that involves different animals. To define animals, we can create an abstract base class called Animal. This base class will contain methods and properties that are common to all animals, such as getting the age and checking if the animal is dead.

In Python, we can define an abstract base class by using the ABC (Abstract Base Class) module. This module provides a helper class called ABC, which we can use to define our base class. We can then use the @abstractmethod decorator to specify which methods should be implemented by the derived classes.

Using abstract base classes has several benefits. First, it enforces a certain structure in the derived classes. By mandating that all derived classes implement the methods and properties defined in the base class, we ensure that they have the necessary functionality. This makes the code more maintainable and reduces the chances of bugs.

Second, abstract base classes cannot be instantiated. They are meant to be inherited by other subclasses. This enforces the concept of inheritance and prevents the creation of instances of the base class itself. This ensures that the base class remains abstract and serves as a blueprint for other classes.

Let's see an example implementation of animal classes using abstract base classes:

from abc import ABC, abstractmethod  
  
class Animal(ABC):  
    @abstractmethod  
    def get_age(self):  
        pass  
  
    @abstractmethod  
    def is_dead(self):  
        pass  
  
class Dog(Animal):  
    def bark(self):  
        print("whoof whoof!!")  
  
    def get_age(self):  
        print("5 years")  
  
     We forgot to declare "is_dead" again  
  

In the above example, we define the Animal class as an abstract base class by inheriting from ABC and using the @abstractmethod decorator for the methods. We also define a derived class called Dog, which inherits from Animal and implements the necessary methods.

If we try to instantiate the Dog class without implementing the is_dead method, we will get a TypeError specifying that the abstract method is not implemented. This ensures that Rule 1 is followed.

bulldog = Dog()  
TypeError: Can't instantiate abstract class Dog with abstract methods is_dead  

Similarly, if we try to instantiate the Animal base class, we will get a TypeError specifying that the abstract class cannot be instantiated. This ensures that Rule 2 is followed.

animal = Animal()  
TypeError: Can't instantiate abstract class Animal with abstract methods get_age, is_dead  

In conclusion, using abstract base classes in Python can greatly improve the structure and maintainability of your code. By enforcing the implementation of specific methods in derived classes and preventing the instantiation of the base class itself, abstract base classes ensure that your class hierarchies are robust and easy to read and maintain.

Here are three actionable advice for using abstract base classes in your code:

  1. Identify common methods and properties: Look for common functionality that can be defined in a base class and make sure to mark them as abstract using the @abstractmethod decorator.

  2. Inherit from ABC: In order to define an abstract base class, inherit from the ABC helper class provided by the abc module. This ensures that the class is recognized as an abstract base class.

  3. Implement all abstract methods: When creating a derived class, make sure to implement all the abstract methods defined in the base class. This ensures that the derived class follows the structure defined by the base class.

By following these three advice, you can leverage the power of abstract base classes to create more maintainable and bug-free class hierarchies in Python.

Sources

← Back to Library

Hatch New Ideas with Glasp AI 🐣

Glasp AI allows you to hatch new ideas based on your curated content. Let's curate and create with Glasp AI :)

Start Hatching 🐣