Pybites Logo Rust Platform

Defining Custom Traits

Medium +3 pts

🎯 In Python, you get polymorphism through duck typing and abstract base classes:

from abc import ABC, abstractmethod class Describable(ABC): @abstractmethod def describe(self) -> str: ... @abstractmethod def tag(self) -> str: ... class Book(Describable): def __init__(self, title, author): self.title = title self.author = author def describe(self) -> str: return f"{self.title} by {self.author}" def tag(self) -> str: return "book"

This is class-based inheritance: Book is a Describable. In Python, the ABC enforces that subclasses implement the …

Login to see the full exercise.