name mangling

Python's renaming of a class attribute whose name starts with two underscores to _ClassName__name.

In more detail

Inside a class body, a name such as __balance that starts with two underscores and does not end with two is stored as _Account__balance. Code outside the class cannot reach it by the plain name, but the mangled name still works, so it prevents accidents rather than providing security. An assignment to obj.__balance written outside the class is not mangled and creates a separate attribute.

Example

class Account:
    def __init__(self):
        self.__balance = 500

print(Account()._Account__balance)   # 500

Related terms

Taught in

References

Certification courses