Home Week 6 6.3 Interfaces (Conceptual)
WEEK 6 LESSON 3 OF 5

Interfaces (Conceptual)

Contracts that guarantee classes will have specific methods.

What is an Interface?

An interface is a contract that says: "Any class implementing me must have these methods." It defines method signatures but provides no implementation. Python does not have a formal interface keyword like Java, but we can simulate them using abstract classes where every method is abstract.

Simulating Interfaces in Python

We create an interface by making an abstract class with only abstract methods -- no concrete methods, no attributes. A class can then implement multiple interfaces.

from abc import ABC, abstractmethod

class Printable(ABC):
    @abstractmethod
    def print_info(self):
        pass

class Saveable(ABC):
    @abstractmethod
    def save(self):
        pass

class Document(Printable, Saveable):
    def __init__(self, title, content):
        self.title = title
        self.content = content

    def print_info(self):
        print(f"Document: {self.title}")
        print(self.content)

    def save(self):
        print(f"Saving {self.title} to disk...")

doc = Document("Report", "Q4 Results...")
doc.print_info()
doc.save()

The Document class implements both the Printable and Saveable interfaces, guaranteeing it has both print_info() and save().

Interface vs Abstract Class

Feature Interface Abstract Class
MethodsAll abstract (only signatures)Mix of abstract and concrete
AttributesNoneCan have attributes
PurposePure contractShared base + contract
MultipleClass can implement manyClass can inherit from many

Practical: Serializable Interface

from abc import ABC, abstractmethod
import json

class Serializable(ABC):
    @abstractmethod
    def to_dict(self):
        pass

    @abstractmethod
    def to_json(self):
        pass

class Student(Serializable):
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def to_dict(self):
        return {"name": self.name, "grade": self.grade}

    def to_json(self):
        return json.dumps(self.to_dict())

s = Student("Alice", "A")
print(s.to_dict())   # {'name': 'Alice', 'grade': 'A'}
print(s.to_json())   # {"name": "Alice", "grade": "A"}

Any class that implements Serializable is guaranteed to have both to_dict() and to_json(). This ensures consistency across your entire codebase.

Why Do Interfaces Matter?

Consistency

All classes implementing an interface are guaranteed to have the same set of methods.

Interchangeability

You can swap one implementation for another without changing the code that uses it.

Best Practices

  • Keep interfaces small and focused -- one responsibility per interface.
  • Name interfaces with adjectives (Printable, Saveable, Serializable) to indicate capability.
  • A class can implement multiple interfaces -- this is safe and encouraged.

Common Mistakes

Adding concrete methods to an interface -- that makes it an abstract class, not an interface.

Creating one massive interface with many methods instead of several small, focused ones.

Confusing Python's informal interfaces (duck typing) with formal interfaces using abc.

Practice Exercises

Exercise 1: Drawable Interface

Create a Drawable interface with a draw() method. Implement it in Circle, Square, and Triangle classes.

Exercise 2: Multiple Interfaces

Create Readable and Writable interfaces. Create a TextFile class that implements both.

Exercise 3: Plugin System

Design a Plugin interface with activate() and deactivate() methods. Create two different plugin classes that implement it.

Summary

  • An interface is a contract -- it defines what methods a class must have.
  • Python simulates interfaces with abstract classes that have only abstract methods.
  • Interfaces differ from abstract classes: no concrete methods, no attributes.
  • Classes can implement multiple interfaces safely.
  • Next up: Multiple Inheritance -- inheriting from more than one parent class.