O'Reilly logo

Expert Python Programming - Second Edition by Tarek Ziadé, Michał Jaworski

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Advanced attribute access patterns

When many C++ and Java programmers first learn Python, they are surprised by Python's lack of a private keyword. The nearest concept is name mangling. Every time an attribute is prefixed by __, it is renamed by the interpreter on the fly:

class MyClass:
    __secret_value = 1

Accessing the __secret_value attribute by its initial name will raise an AttributeError exception:

>>> instance_of = MyClass()
>>> instance_of.__secret_value
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute '__secret_value'
>>> dir(MyClass)
['_MyClass__secret_value', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required