Abstract Properties

We can use @property decorator and @abc.abstractmethod  to declare properties as an abstract class. Let’s look into the below code.

Python3




import abc
  
  
class AbstractClass(metaclass=abc.ABCMeta):
    @property
    @abc.abstractmethod
    def abstractName(self):
        pass
  
  
class ValidSubClass(AbstractClass):
    @property
    def abstractName(self):
        return 'Abstract 1'
  
  
vc = ValidSubClass()
print(vc.abstractName)


Output:

Abstract 1

Abstract Base Class (abc) in Python

Have you ever thought about checking whether the objects you are using adheres to a particular specification? It is necessary to verify whether an object implements a given method or property, especially while creating a library where other developers make use of it. A developer can use hasattr or isinstance methods to check whether the input conforms to a particular identity. But sometimes it is inconvenient to use those methods to check a myriad of different properties and methods.    

As a solution to this inconvenience, Python introduced a concept called abstract base class (abc). In this section, we will discuss the abstract base class and its importance.  

  • Abstract Base Class
  • Declaring an Abstract Base Class
  • Why declare an Abstract Base Class?
  • Abstract Properties
  • Built-In Abstract Classes

Similar Reads

Abstract Base Class

The main goal of the abstract base class is to provide a standardized way to test whether an object adheres to a given specification. It can also prevent any attempt to instantiate a subclass that doesn’t override a particular method in the superclass. And finally, using an abstract class, a class can derive identity from another class without any object inheritance....

Declaring an Abstract Base Class

Python has a module called abc (abstract base class) that offers the necessary tools for crafting an abstract base class. First and foremost, you should understand the ABCMeta metaclass provided by the abstract base class. The rule is every abstract class must use ABCMeta metaclass....

Why Declare an Abstract Base Class?

...

Abstract Properties

...

Built-in Abstract classes

To understand the need to declare a virtual subclass, we need to consider the example of a list-like object where you don’t want to put a restriction of only considering list or tuple. Before that let’s see how to use isinstance to check against a list or tuple of class....

Summary

...

Contact Us