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
__namedoes to an attribute's name, and reach it anyway - Choose between a public name,
_nameand__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.
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.
- Line 4 starts every book on the shelf.
lend()on line 6 is the only code that sets_on_loantoTrue, 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.
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.
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:
- +title: str
- −__isbn
- +__init__(title: str, isbn: str)
- +describe(): str
- Class Book; attributes: title, __isbn; methods: __init__, describe.
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.
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.
| Name | What it says | What Python does |
|---|---|---|
title | Public: for anyone to read and use | Nothing |
_on_loan | Internal: the object’s own business. Outside code shouldn’t touch it | Nothing. It’s a note to people |
__isbn | Internal, and kept apart from a child class’s names | Renames 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.
| Python | Java | Rust | |
|---|---|---|---|
| Public | Every name, unless it starts with _ | public, written on the field | pub, written on the field |
| Internal | _name: a convention, not checked | private (and protected for child classes) | Every field without pub: the default |
| Who can reach internal data | Anyone who ignores the underscore | Only the class’s own code | Only code in the same module |
| Breaking the rule | Runs. Python trusts you | The compiler refuses | The 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.
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.
- The Python Tutorial: Private Variables: the underscore convention and name mangling
- The Python Language Reference: Private name mangling
- PEP 8: Descriptive naming styles: _single_leading_underscore and __double_leading_underscore
- PEP 8: Designing for Inheritance: public or non-public, and when to use two underscores
- Built-in Functions: vars
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- The Java Tutorials: Controlling Access to Members of a Class: public, protected and private in Java
- The Rust Reference: Visibility and Privacy: Rust items are private unless marked pub