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