Object-oriented programming · lesson 2 of 17
Parts in this lesson
Adune.copiespublic: anyone can read or change it
Bself._on_loanone underscore: please don't touch
Cself.__isbntwo underscores: Python renames it
Ddune._Book__isbnthe name it really has

Public, “protected” and “private”

Last updated

Lesson 3.P ended with a problem: any line of the program can write dune.copies = -5. Many languages let a class lock its data away. Python doesn't. In this lesson you'll see what Python leaves open, mark an attribute as the object's own business with one underscore, watch outside code ignore that and lend one book twice, meet the two-underscore names Python renames for you, and find out what that renaming is really for.

By the end of this lesson you can

  • Explain why an object should be the only code that changes its own data
  • Mark an attribute as internal with _name, and say what Python does and doesn't stop
  • Say what __name does to an attribute's name, and reach it anyway
  • Choose between a public name, _name and __name

Why hide an object's insides

Every attribute you've written so far is public: any line of the program can read it, change it, or add new ones. Here's the Book from lesson 3.3, whose lend() refuses to go below zero copies. Run it.

Step 1 code main.py
Edit the code, then run it again

lend() on line 13 follows the rule, and leaves 0 copies. Then line 15 sets copies to -5 from outside, line 17 sets it to some text, and line 18 gives the book an attribute the class never mentioned. Python lets all of it happen, and line 19 shows the result. The rule in lend() only protects the book if every change goes through lend().

That's the reason to hide an object's insides. If only the object's own methods change its data, the rules live in one place, and nothing else can break them. Some of the data is for everyone: a book's title. Some is the book's own business: how it keeps track of its copies. Python has ways to say which is which, but as you'll see, it trusts you to respect them.

_name: please don't touch

An attribute whose name starts with one underscore, like _on_loan, is internal. It tells anyone reading the code: "this belongs to the object; use its methods instead". This book has one copy, and _on_loan records whether it's out.

Step 2 code main.py
Edit the code, then run it again
  • Line 4 starts every book on the shelf.
  • lend() on line 6 is the only code that sets _on_loan to True, and it refuses if the book is already out (line 8). give_back() on line 11 sets it back.
  • where() on line 14 reads it, so outside code never needs to.

Outside the class, the program only uses lend(), give_back() and where(). You'll sometimes hear _name called "protected", a word from other languages for "for this class and its children". In Python the underscore is a convention: an agreement between programmers. Python itself treats _on_loan like any other name.

Touching it anyway

Sam has borrowed Dune. The desk wants Ana to have it as well, so someone takes a shortcut and sets _on_loan back to False from outside. Run it.

Step 3 code main.py
Edit the code, then run it again

An underscore is a sign on a door, not a lock. When you see thing._name outside thing's class, treat it as a warning: this code depends on something the class's author was free to change or remove.

__name and name mangling

A name that starts with two underscores (and doesn't end with two, like __init__ does) gets special treatment inside a class. This book keeps its ISBN in __isbn. Run it.

Step 4 code main.py
Edit the code, then run it again

Line 11 works: describe() reads self.__isbn from inside the class. Line 12 stops with AttributeError: 'Book' object has no attribute '__isbn'. The book has no attribute by that name.

When Python reads a class, it renames every __name written inside it to _ClassName__name. This is called name mangling. So line 4 really set self._Book__isbn, and line 7 really reads self._Book__isbn. Line 12 is outside the class, so nothing is renamed, and Python looks for __isbn, which doesn't exist.

The renamed attribute is still there, and anyone can use it:

Book, with + for a public name and − for a private one
Book
  • +title: str
  • −__isbn
  • +__init__(title: str, isbn: str)
  • +describe(): str
  • Class Book; attributes: title, __isbn; methods: __init__, describe.
Step 4 code main.py
Edit the code, then run it again

Line 11 shows the book's real attributes, and line 12 reads the ISBN by its mangled name. Line 13 even changes it, and describe() on line 14 prints the nonsense. Two underscores make the name awkward to reach. They don't make it private.

What mangling is really for

If mangling doesn't hide anything, why does Python do it? To keep a class's names apart from the names of the classes built on it.

One new piece of syntax: class DVD(LibraryItem): makes a class built on top of LibraryItem. A DVD gets every method LibraryItem has, and can add its own. Lesson 4.5 teaches this properly. Here, LibraryItem counts loans in __count, and DVD, written later by someone else, uses __count for the number of discs in the case.

Step 5 code main.py
Edit the code, then run it again

Line 4 sets _LibraryItem__count, and line 13 sets _DVD__count. They're two attributes, as line 20 shows, so the discs and the loans don't get mixed up, and lines 18 and 19 count loans 1 and 2.

Change both __counts to _count and run it again. Now there's one attribute: line 17 sets it to 3, and the loans count on from there, printing 4 and 5. The person writing DVD would have to know every internal name in LibraryItem to avoid this. Two underscores mean they don't have to.

We're all consenting adults

So Python has no private attributes at all. Python programmers have a saying about this: "we're all consenting adults here". The language trusts you to read an underscore and respect it, and in return you can still reach inside when you really need to, in a test or while debugging.

Three kinds of name
NameWhat it saysWhat Python does
titlePublic: for anyone to read and useNothing
_on_loanInternal: the object’s own business. Outside code shouldn’t touch itNothing. It’s a note to people
__isbnInternal, and kept apart from a child class’s namesRenames it to _Book__isbn. Nothing else

Here's how to choose:

  • Make an attribute public when outside code is meant to use it, like title.
  • Start it with one underscore when it's the object's own business, like _on_loan. This is the usual choice for internal data.
  • Use two underscores only when a class is meant to be built on and you need to keep its names out of the way of child classes' names. Most code never needs them.

A public attribute is a promise: other code will use it, and can set it to anything. When a value has rules, keep it in a _name and let other code reach it through methods. Lesson 4.3 writes those methods: getters and setters.

In other languages

This step is optional. It's for anyone who will meet Java, C# or Rust later.

Hiding the insides in three languages
PythonJavaRust
PublicEvery name, unless it starts with _public, written on the fieldpub, written on the field
Internal_name: a convention, not checkedprivate (and protected for child classes)Every field without pub: the default
Who can reach internal dataAnyone who ignores the underscoreOnly the class’s own codeOnly code in the same module
Breaking the ruleRuns. Python trusts youThe compiler refusesThe compiler refuses

C# works like Java here. In Java, C# and Rust, line 15 of step 3 wouldn't compile: the field is private, and the compiler stops any code outside the class (or, in Rust, outside the module) from touching it. Python checks nothing, and leaves it to you. Simple Rust 4.2 hides a field the Rust way, with modules and pub.

Check what you learned

Three questions. Pick or type an answer, then check it.

Outside the class, a program runs dune._on_loan = False. What does Python do?
What does this program print?
class Member:
    def __init__(self, name):
        self.name = name
        self.__pin = "1234"


sam = Member("Sam")
print(list(vars(sam)))
You're writing a Member class. Which name should its list of loans have, if outside code should use the member's methods instead of the list?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python