Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 149 ยท Object-Oriented Programming

OOP Principles: Encapsulation, Polymorphism and Abstraction

Apply core OOP principles in Python. Learn encapsulation with _ and __ name mangling, polymorphism and duck typing, abstraction, composition vs inheritance.

You now know the mechanics of Python classes: methods, inheritance, special methods, properties, abstract classes and protocols. This lesson steps back and asks a different question: how do you design classes well?

Object-oriented programming is usually described with four principles: encapsulation, abstraction, inheritance and polymorphism. Python supports all four, but in its own relaxed way. There are no private or public keywords, and no compiler checks that a class "implements an interface". Instead, Python relies on conventions and a philosophy often summed up as "we're all consenting adults here". You'll learn what each principle means, how Python expresses it, and why most experienced developers prefer composition over deep inheritance trees.

Encapsulation: keep the rules inside the object

Encapsulation means bundling data with the methods that work on it, and making sure the data can only change in ways that keep it valid. The rules that must always hold for an object are called its invariants: a bank account's balance never goes below zero, a date's month stays between 1 and 12.

Compare these two designs. In the first, any code can break the invariant. In the second, the object protects it:

Python Protecting an invariant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every change to Account goes through deposit() or withdraw(), so the checks live in one place and the history can't fall out of step with the balance. That's encapsulation's real payoff: you can reason about an object by reading its class, without hunting through the whole program for code that pokes at its fields.

The single underscore convention

Notice that the last line could still read acct._history. Python doesn't block access. A leading underscore is a convention that means "internal: not part of the public interface; may change without notice". Everyone who reads Python code knows it, and tools respect it:

  • from module import * skips names that start with _.
  • Editors and documentation tools hide or de-emphasize them.
  • Linters warn when you access another object's _name.

So the Python way is: public attributes have plain names, internal ones start with _, and when outside code needs controlled access, you add a method or a property instead of making the attribute public. Start with plain public attributes for simple data. You can always turn one into a property later without changing any calling code.

Double underscores and name mangling

Two leading underscores (and at most one trailing) trigger name mangling: inside a class body, Python rewrites __name to _ClassName__name. Its purpose isn't secrecy; it's to stop subclasses from accidentally overwriting an attribute that a parent class relies on:

Python Name mangling prevents clashes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The parent's describe() still sees its own __secret, because inside Widget the name means _Widget__secret. But the plain _id was silently replaced by the subclass.

Use double underscores rarely: in classes designed to be subclassed by other people, for internals that must not collide. They make debugging and testing slightly awkward. And don't confuse them with dunder names like __init__, which have underscores on both sides and are never mangled.

Abstraction: a simple interface over messy details

Abstraction means exposing what an object does while hiding how. You call file.read() without knowing about disk sectors, and sorted() without knowing which algorithm it uses. Good classes do the same: a few well-named methods, with the complexity behind them.

Python Hiding the details behind a small interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Callers only know record(), average() and warmest(). Tomorrow you could store readings in a database or keep running totals instead of lists, and no calling code would change. Normalizing city names happens in one place instead of everywhere.

Abstract base classes take this one step further: they define an interface on its own (say, a Storage with save() and load()) that several concrete classes implement. Protocols do the same without requiring inheritance.

Polymorphism: one interface, many forms

Polymorphism means code can work with objects of different types through the same interface. You've used it constantly: len() works on strings, lists and dictionaries; + adds numbers and joins strings; for loops over anything iterable.

In your own code, polymorphism usually comes from classes that share method names, either through inheritance (overriding a parent's method) or simply by having the same methods. That second style is duck typing, and it's the most Pythonic form:

Python Polymorphism with duck typing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

total_area() never asks what type each item is. Adding a new shape means writing one new class, not editing an if isinstance(...) chain in every function that handles shapes. When you see a long chain of type checks, it's often a sign that the behavior belongs in methods on those types.

Overloading by type with singledispatch

Some languages let you define several versions of a function with different parameter types. Python doesn't: a second def with the same name simply replaces the first. When you need different behavior for types you don't control (built-ins, library classes), use functools.singledispatch:

Python functools.singledispatch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

singledispatch picks the implementation based on the type of the first argument, using the type annotation of each registered function. For methods, there's functools.singledispatchmethod.

Composition vs inheritance

Inheritance models an "is a" relationship and shares code by extending a parent class. Composition models "has a": an object holds other objects and delegates work to them. Both are useful, but inheritance couples classes tightly: the subclass depends on the parent's internal behavior, not just its public methods. Here's a classic trap:

Python Why inheriting from built-ins bites

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

dict is written in C, and its update() and constructor don't go through your __setitem__. The subclass only works if you know the parent's internals. collections.UserDict exists precisely for this: it's written so that every operation routes through the methods you override. The broader lesson is that inheritance exposes you to your parent's implementation details.

Composition avoids that coupling. Instead of being a list, a class can have a list and expose only the operations that make sense:

Python Composition and swappable parts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reminders doesn't inherit from a sender or from list. It holds them. You can swap the sender at runtime, test with a fake, and nobody can call list methods like sort() or insert(0, ...) that would make no sense for a reminder queue.

A practical guide for choosing:

  • Use inheritance for a genuine "is a" relationship where the subclass can be used anywhere the parent is expected: custom exceptions, specialized views in a framework, implementations of an abstract base class. Keep hierarchies shallow (one or two levels).
  • Use composition for "has a" or "uses a" relationships, for swappable behavior (senders, storage, pricing rules), and whenever you'd only inherit to reuse a few methods.
  • Mixins are a middle ground: small classes that add one capability (such as JsonMixin with a to_json() method) through multiple inheritance. They work well when each mixin is small and independent.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a single leading underscore, as in self._cache, mean in Python?

    Python doesn't enforce it, but every Python developer and many tools treat _name as internal.
  2. 2. Inside class Engine, you write self.__rpm = 0. Under what name is the attribute stored?

    Name mangling rewrites __name to _ClassName__name so subclasses can't clash with it by accident.
  3. 3. A function has a long chain of if isinstance(x, A): ... elif isinstance(x, B): .... Which principle usually offers a cleaner design?

    When each type implements the behavior itself, callers just call the method and new types need no edits elsewhere.
  4. 4. You subclass dict and override __setitem__. Why might d.update(...) ignore your override?

    Inheriting from built-ins ties you to their internal implementation. collections.UserDict routes everything through the overridable methods.
  5. 5. A report class needs to send results by email, SMS or a test fake. Which design fits best?

    The report HAS a sender. Composition lets you swap senders at runtime and in tests without changing the report class.

Summary

  • Encapsulation keeps an object's data valid by routing changes through its methods; _name marks internals by convention, and properties give controlled access.
  • __name triggers name mangling to _ClassName__name, which prevents accidental clashes in subclasses; it isn't real privacy and should be used sparingly.
  • Abstraction exposes a small, meaningful interface and hides how it works, so the internals can change freely.
  • Polymorphism lets one piece of code work with many types through shared method names; duck typing is the Pythonic form, and functools.singledispatch handles type-based dispatch for functions.
  • Inheritance couples a subclass to its parent's internals (subclassing dict is the classic trap); prefer composition for "has a" relationships and swappable behavior, and keep inheritance shallow.

Next: Metaclasses, Descriptors and Object Internals, where you'll look under the hood at how attributes, methods and classes themselves work.