liveBook · Manning

Private member

As explained in The Quick Python Book, Fourth Edition

A private instance variable is an instance attribute represented by a name-mangled identifier intended to restrict direct access from subclasses.

A private instance variable is an attribute whose name begins, but does not end, with two underscores. Python mangles that name to reduce accidental access and signal that the attribute belongs to the class’s internal implementation. section 15.9

Private members provide several practical guarantees:

  • Restrict ordinary direct access from outside the defining class, supporting security, reliability, and clearer interfaces. section 15.9
  • Avoid inheritance name clashes: a subclass and superclass can use the same private name while retaining separate attributes. section 15.9 section 15.11
  • Expose internal state through an ordinary method when controlled access is appropriate; deliberate access remains possible by reproducing the mangled name. section 15.9

A private attribute in practice

class Mine: def __init__(self): self.x = 2 self.__y = 3 def print_y(self): print(self.__y) m = Mine() print(m.x) # 2 m.print_y() # 3 print(m.__y) # AttributeError The attribute appears in dir(m) under the mangled name _Mine__y. This is an access barrier against accidents, not an absolute security boundary.

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains naming rules, access behavior, inheritance effects, and name mangling, but stops short of treating privacy as absolute.
Examples
Demonstrates public and private attributes through Mine, print_y, direct-access failure, dir output, and class-namespace listings.
What it assumes
Assumes familiarity with classes, instances, methods, and inheritance while teaching private-member syntax and behavior directly.
What you can do after
Apply it via Python double-underscore naming, access the value through class methods, and recognize the resulting AttributeError.
How it connects
Connects private members to instance variables, methods, inheritance, class namespaces, 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 The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.