liveBook · Manning

Private member

As explained in Python How-To

A private method is a class method intended for internal use whose name or access convention discourages or restricts direct access by callers.

A private method keeps implementation details inside a class so users see only the operations they need. In Python, prefix the method name with two underscores, as in __format_note. section 8.3 section 8.3.2

Use private methods when the class should control an operation’s public visibility:

  • Call the private method from other methods inside its class, while exposing a clearer public operation such as complete(). section 8.3.2
  • Remember that Python permits deliberate access through the mangled name, such as task._Task__format_note(...); privacy is restrictive rather than absolute. section 8.3.2
  • Choose protected methods instead when subclasses should inherit and use the helper; choose private methods when subclasses should not access it. section 8.5.4

Formatting an internal note

class Task:\n def complete(self, note=""):\n self.note = self.__format_note(note)\n\n def __format_note(self, note):\n return note.title()\n\ntask = Task()\ntask.complete("a note")\n# task.note == "A Note" section 8.3.2

How Python How-To covers it

How deep it goes
Explains double-underscore syntax, external access errors, name mangling, and subclass behavior, while noting privacy is not absolute.
Examples
Demonstrates Task.__format_note and Employee.__transfer_group alongside protected-method comparisons.
What it assumes
Assumes basic classes and methods while introducing encapsulation and public, protected, and private access distinctions.
What you can do after
Build it from scratch by defining double-underscore helpers and choosing private or protected access for inheritance needs.
How it connects
Connects private methods to encapsulation, protected methods, inheritance, subclasses, and name mangling.

Also explained in

Compare how 12 books explain private member →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.