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 abstract methods. Without ABC, duck typing handles it — if it has describe(), it's describable.

Rust uses traits instead of inheritance. A trait defines behavior that types can implement:

trait Describable {
    fn describe(&self) -> String;
    fn tag(&self) -> &str;
}

The key difference: traits are implemented for types, not inherited by them. Any type …

Login to see the full exercise.