|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# 34-abstractclasses-1.py |
| 4 | + |
| 5 | +# This code snippet talks about Abstract Base Classes (abc). |
| 6 | + |
| 7 | +# The `abc` module provides features to create |
| 8 | +# Abstract Base Classes. |
| 9 | + |
| 10 | +# To create an Abstract Base Class, set the `__metaclass__` magic method |
| 11 | +# to `abc.ABCMeta`. This will mark the respective class as an Abstract |
| 12 | +# Base Class. |
| 13 | + |
| 14 | +# Now, in order to specify the methods which are to be enforced on the |
| 15 | +# child classes, ie.. to create Abstract Methods, we use the decorator |
| 16 | +# @abc.abstractmethod on the methods we need. |
| 17 | + |
| 18 | +# The child class which inherits from an Abstract Base Class can implement |
| 19 | +# methods of their own, but *should always* implement the methods defined in |
| 20 | +# the parent ABC Class. |
| 21 | + |
| 22 | +# NOTE: This code will error out. This is an example on what |
| 23 | +# happens when a child class doesn't implement the abstract methods |
| 24 | +# defined in the Parent Class. |
| 25 | + |
| 26 | +import abc |
| 27 | + |
| 28 | + |
| 29 | +class My_ABC_Class(object): |
| 30 | + __metaclass__ = abc.ABCMeta |
| 31 | + |
| 32 | + @abc.abstractmethod |
| 33 | + def set_val(self, val): |
| 34 | + return |
| 35 | + |
| 36 | + @abc.abstractmethod |
| 37 | + def get_val(self): |
| 38 | + return |
| 39 | + |
| 40 | +# Abstract Base Class defined above ^^^ |
| 41 | + |
| 42 | +# Custom class inheriting from the above Abstract Base Class, below |
| 43 | + |
| 44 | + |
| 45 | +class MyClass(My_ABC_Class): |
| 46 | + |
| 47 | + def set_val(self, input): |
| 48 | + self.val = input |
| 49 | + |
| 50 | + def hello(self): |
| 51 | + print("\nCalling the hello() method") |
| 52 | + print("I'm *not* part of the Abstract Methods defined in My_ABC_Class()") |
| 53 | + |
| 54 | +my_class = MyClass() |
| 55 | + |
| 56 | +my_class.set_val(10) |
| 57 | +print(my_class.get_val()) |
| 58 | +my_class.hello() |
0 commit comments