Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Challenge: Refactoring an ABC to a Protocol | Protocols vs ABCs
Python Abstract Base Classes
Seção 3. Capítulo 4
single

single

Challenge: Refactoring an ABC to a Protocol

Deslize para mostrar o 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"
Tarefa

Deslize para começar a programar

  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.

Solução

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 4
single

single

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

some-alt