Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Refactoring an ABC to a Protocol | Protocols vs ABCs
Python Abstract Base Classes
Section 3. Chapter 4
single

single

Challenge: Refactoring an ABC to a Protocol

Swipe to show menu

You are given an existing ABC-based interface and two classes that currently inherit from it. Your task is to create an equivalent Protocol, verify that both classes satisfy it without inheritance, and compare isinstance() behavior between the two approaches.

You are given the following existing code:

from abc import ABC, abstractmethod

class Transformer(ABC):
    @abstractmethod
    def transform(self, data):
        pass

    @abstractmethod
    def get_name(self):
        pass

class UpperCaseTransformer(Transformer):
    def transform(self, data):
        return [item.upper() for item in data]

    def get_name(self):
        return "UpperCase"

class TrimTransformer(Transformer):
    def transform(self, data):
        return [item.strip() for item in data]

    def get_name(self):
        return "Trim"
Task

Swipe to start coding

  1. Import Protocol and runtime_checkable from typing.
  2. Define a @runtime_checkable Protocol called TransformerProtocol with two methods: transform(self, data) and get_name(self), both with ... as their body.
  3. Define a new class ReverseTransformer (do not inherit from Transformer or TransformerProtocol) with:
    • transform(self, data) that returns a list of reversed strings: [item[::-1] for item in data];
    • get_name(self) that returns "Reverse".
  4. Create instances: upper = UpperCaseTransformer(), trim = TrimTransformer(), reverse = ReverseTransformer().
  5. Store the following in variables:
    • upper_abc = isinstance(upper, Transformer);
    • reverse_abc = isinstance(reverse, Transformer);
    • upper_proto = isinstance(upper, TransformerProtocol);
    • reverse_proto = isinstance(reverse, TransformerProtocol).
  6. Print all four variables.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 4
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt