Practice: Abstraction

« Read the chapter

Q1. First abstract class

BeginnerCoding

Create abstract class Animal with abstract method sound(). Create Dog that returns 'Woof'. Print Dog().sound().

Goal: Create an abstract class.

Q2. Vehicle contract

BeginnerCoding

Create abstract class Vehicle with abstract method wheels(). Make Car (4) and Bike (2). Print the wheels of both on separate lines.

Goal: Implement abstract methods.

Q3. Catch the error

IntermediateCoding

Create an abstract class Base with abstract method go(). Try to create Base() and print 'abstract' when TypeError is raised.

Goal: Know instantiation rules.

Q4. Template method

IntermediateCoding

Write abstract class Greeter with a concrete method greet() returning 'Hello, ' + self.name(), and abstract method name(). Create Ravi returning 'Ravi'. Print Ravi().greet().

Goal: Use a template method.

Q5. Payment contract

IntermediateCoding

Create abstract class Payment with abstract pay(amount). Create Card returning 'Card paid 50' and Cash returning 'Cash paid 50'. Print the result of pay(50) for both.

Goal: Design with an abstract contract.

Q6. Check relationship

AdvancedCoding

Create abstract class A, a child B(A) implementing nothing abstract (A has no abstract methods), and print isinstance(B(), A) and issubclass(B, A) on separate lines.

Goal: Check class relationships.

Q7. Concrete child

BeginnerOutput

What does this print?

Code
from abc import ABC, abstractmethod
class A(ABC):
    @abstractmethod
    def f(self):
        pass
class B(A):
    def f(self):
        return "ok"
print(B().f())

Goal: Read ABC code.

Q8. Incomplete child

IntermediateOutput

What is printed?

Code
from abc import ABC, abstractmethod
class A(ABC):
    @abstractmethod
    def f(self):
        pass
class B(A):
    pass
try:
    B()
except TypeError:
    print("TypeError")

Goal: Spot missing overrides.

Q9. Shared method

IntermediateOutput

What does this print?

Code
from abc import ABC, abstractmethod
class A(ABC):
    def run(self):
        return self.step() * 2
    @abstractmethod
    def step(self):
        pass
class B(A):
    def step(self):
        return 21
print(B().run())

Goal: Template methods.

Q10. Abstract with body

AdvancedOutput

What is the output?

Code
from abc import ABC, abstractmethod
class A(ABC):
    @abstractmethod
    def hi(self):
        return "base"
class B(A):
    def hi(self):
        return super().hi() + "+child"
print(B().hi())

Goal: Abstract bodies.

Q11. isinstance check

BeginnerOutput

What is printed?

Code
from abc import ABC
class A(ABC): pass
class B(A): pass
print(isinstance(B(), A), isinstance(A(), B))

Goal: Check inheritance.

Q12. Abstract property

AdvancedOutput

What does this print?

Code
from abc import ABC, abstractmethod
class A(ABC):
    @property
    @abstractmethod
    def n(self):
        pass
class B(A):
    @property
    def n(self):
        return 7
print(B().n)

Goal: Abstract properties.

Q13. Forgot ABC

IntermediateDebugging

This code should refuse to create Base(), but does not. Fix it so it prints 'blocked'.

Code
from abc import abstractmethod
class Base:
    @abstractmethod
    def go(self):
        pass
try:
    Base()
    print("created")
except TypeError:
    print("blocked")

Goal: Use ABC correctly.

Q14. Missing implementation

BeginnerDebugging

Creating Cat fails with TypeError. Fix it so it prints 'Meow'.

Code
from abc import ABC, abstractmethod
class Pet(ABC):
    @abstractmethod
    def sound(self):
        pass
class Cat(Pet):
    def noise(self):
        return "Meow"
print(Cat().sound())

Goal: Match the contract.

Q15. Import mistake

BeginnerDebugging

The abstract method decorator is not found. Fix the import so it prints 'fine'.

Code
from abc import ABC
class A(ABC):
    @abstractmethod
    def f(self):
        pass
class B(A):
    def f(self):
        pass
print("fine")

Goal: Fix imports.

Q16. Abstraction vs encapsulation

IntermediateConceptual

State the difference between abstraction and encapsulation in two sentences.

Goal: Tell the concepts apart.

Q17. Why abstract classes?

AdvancedConceptual

Give two reasons to use an abstract base class instead of relying only on duck typing.

Goal: Know when ABCs help.

Q18. Export formats

IntermediateApplication

Application: abstract class Exporter has abstract export(data). CsvExporter returns ','.join(data) and PipeExporter returns '|'.join(data). Print both results for ['a', 'b', 'c'].

Goal: Apply abstraction.