Editor

Multi-Method Protocol: Renderable

Advanced · Write the code · from Python Protocols: Duck Typing with Type Safety

From the lesson: Python Protocols: Duck Typing with Type Safety

Python has a famous saying: "If it walks like a duck and quacks like a duck, then it's a duck." This is called duck typing - you don't care what an object is, only what it can do. But duck typing has a downside: your editor and type checker have no idea what you expect.

Read the lesson

Create a Renderable Protocol with two methods:

  • render() -> str
  • size() -> int
  • Then create a Paragraph class whose __init__ takes a text string. Its render() returns "<p>{text}</p>" and its size() returns the length of the text.

    Create a Header class whose __init__ takes a text string. Its render() returns "<h1>{text}</h1>" and its size() returns the length of the text.

    Write a function display(item) that prints the render output and then prints the size.

    Call display with Paragraph('Hello') and then Header('Title').

    from typing import Protocol
    # Define Renderable Protocol with render() and size()
    # Define Paragraph class
    # Define Header class
    # Define display function
    # Call display with both objects

    More Protocol exercises

    All Python exercises · 50 practice problems · Advanced Python quiz