Code Explanation:
1. Importing ABC Tools
from abc import ABC, abstractmethod
Imports:
ABC → Base class for creating abstract classes
abstractmethod → Decorator to mark methods as mandatory to override
๐ Used to enforce method implementation in subclasses.
๐น 2. Defining an Abstract Base Class A
class A(ABC):
A inherits from ABC
This makes A an abstract class
Abstract classes cannot be instantiated directly
๐น 3. Declaring an Abstract Method
@abstractmethod
def f(self): pass
Declares f() as an abstract method
Any concrete subclass must provide an implementation
pass means no implementation in A
๐ If a subclass doesn’t implement f, it cannot be instantiated
๐น 4. Defining Subclass B
class B(A):
B inherits from abstract class A
Python checks whether B implements all abstract methods
๐น 5. Implementing the Abstract Method (Tricky Part)
f = lambda self: 10
Assigns a function object to f
This counts as implementing the abstract method
Equivalent to:
def f(self):
return 10
๐ Python does not care about syntax, only that f exists and is callable.
๐น 6. Creating an Object of B
B()
Allowed because:
All abstract methods are implemented
B is now a concrete class
๐น 7. Calling the Method
print(B().f())
Step-by-step:
B() → creates an instance of B
.f() → calls the lambda method
Lambda returns 10
print() prints the value
✅ Final Output
10

0 Comments:
Post a Comment