Code:
from abc import ABC, abstractmethod
class Test(ABC):
@abstractmethod
def show(self):
pass
obj = Test()
Explanation:
๐น 1. Importing ABC and abstractmethod
from abc import ABC, abstractmethod
✅ Explanation
Python imports two special objects from the abc (Abstract Base Class) module.
ABC is used to create an Abstract Base Class.
@abstractmethod is used to declare methods that must be implemented by child classes.
Think of it like an architect's blueprint.
Architect Blueprint
↓
Must have:
✔ Door
✔ Window
✔ Roof
You cannot live inside a blueprint.
Similarly,
ABC
↓
Defines rules
↓
Cannot be used directly
๐น 2. Creating an Abstract Class
class Test(ABC):
✅ Explanation
Here, Test inherits from ABC.
This tells Python:
"This is not a normal class.
This is an Abstract Class."
Visual:
ABC
│
▼
Test
(Abstract Class)
Unlike a normal class, this class is meant to be inherited, not instantiated.
๐น 3. Using @abstractmethod
@abstractmethod
✅ Explanation
This decorator marks the next method as abstract.
Meaning:
Every child class
MUST
implement this method.
It is like creating a rule.
Example:
School Rule
Every student
must submit homework.
Similarly,
Every child class
must implement show()
๐น 4. Defining the Abstract Method
def show(self):
✅ Explanation
A method named show() is declared.
But notice...
It has no implementation.
It only defines:
Method name
Parameters
Actual logic will be written by child classes.
Visual:
show()
↓
Only Declaration
↓
No Code Yet
๐น 5. Using pass
pass
✅ Explanation
pass means:
"Do nothing."
Python requires every function to have a body.
Since the method is abstract, we leave it empty using pass.
Equivalent idea:
Coming Soon...
No implementation yet.
๐น 6. Current Class Structure
At this point, Python has created:
Test
│
└── show()
(Abstract Method)
Notice:
show()
↓
No implementation
Therefore the class is incomplete.
๐น 7. Creating an Object
obj = Test()
✅ Explanation
Python now tries to create an object.
Internally:
Create Object
↓
Check Class
↓
Does it contain abstract methods?
↓
YES
Python immediately stops.
๐น 8. Why Does Python Raise an Error?
Because Test still has an abstract method.
Python says:
You promised that
show()
would be implemented,
but it isn't.
So object creation is not allowed.
❌ Error Produced
TypeError:
Can't instantiate abstract class Test
with abstract method show
๐ฏ Final Output
TypeError:
Can't instantiate abstract class Test
with abstract method show

0 Comments:
Post a Comment