Code Explanation:
1. Importing Abstract Class Tools
from abc import ABC, abstractmethod
Imports utilities from Python’s abc module
ABC → base class used to create abstract base classes
abstractmethod → decorator to declare mandatory methods
๐น 2. Defining Abstract Base Class A
class A(ABC):
Class A inherits from ABC
This makes A an abstract class
Abstract classes cannot be instantiated
๐น 3. Declaring an Abstract Method
@abstractmethod
def f(self): pass
Declares method f() as abstract
No implementation is provided (pass)
Any subclass of A must implement f()
๐ This enforces a contract:
“Every concrete subclass must define f()”
๐น 4. Defining Subclass B
class B(A):
pass
B inherits from abstract class A
B does NOT implement the abstract method f
Therefore, B is still an abstract class
๐ Even though B is a subclass, it remains abstract.
๐น 5. Creating an Object of B
B()
Python checks:
Are there any unimplemented abstract methods? → Yes (f)
Instantiation is not allowed
❌ Runtime Error Raised
TypeError: Can't instantiate abstract class B with abstract method f

0 Comments:
Post a Comment