Reading preferences
Concept

Encapsulation, Polymorphism, and Abstraction

Design small object interfaces and see how overriding changes behaviour.

python, oop, encapsulation, polymorphism, abstraction, overriding

An interface can have several implementations

Imagine asking different notifiers to deliver a message. The caller needs a send operation; it need not know how each notifier formats the message. This shared operation is an abstraction, while different implementations of it illustrate polymorphism.

Python illustration

class Notifier:
    def send(self, message):
        return f"Notice: {message}"

class StudyNotifier(Notifier):
    def send(self, message):
        return f"Study: {message}"

def announce(notifier, message):
    return notifier.send(message)

print(announce(Notifier(), "Read"))
print(announce(StudyNotifier(), "Read"))

Prepared output — not live execution:

Notice: Read
Study: Read

The second class overrides send. The same announce function calls the appropriate implementation for the object it receives.

See the reasoning

Follow the example one step at a time

See one caller use two implementations of the same operation. This is a prepared teaching demonstration, not live code execution.

Choose an interface

announce(notifier, message) → notifier.send(message)

The caller needs an object with a suitable send method.

Protect a useful boundary

Encapsulation groups state with the operations that manage it. For example, a counter can expose an increment method rather than asking every caller to enforce its rules. A leading underscore, as in _count, signals an internal detail by convention; it is not access control. A double leading underscore invokes name mangling, not security.

class Counter:
    def __init__(self):
        self._count = 0

    def increment(self):
        self._count += 1

    def value(self):
        return self._count

counter = Counter()
counter.increment()
print(counter.value())  # 1

Callers use the methods to change and inspect the state, but Python does not prevent someone from accessing _count directly.

Python often uses duck typing: an object works if it provides the operation the caller needs, even without inheriting a particular class. Interfaces should document expected behaviour and errors. An abstract base class can formalise a contract; its more advanced mechanics are covered later.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What is the goal of encapsulation?
2. What allows two different objects to respond to the same method call?
3. What happens when a subclass defines a method with the same name as its parent?
4. What does an abstraction emphasise?

References and further reading