Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Access a Name-Mangled Private Attribute

Learn how Python name-mangles double-underscore attributes and implement a helper that retrieves values whether they are public, protected, or name-mangled private.

Python practice15 minEncapsulation & Access PatternsIntermediateLast updated April 8, 2026

Problem statement

In Python, attributes prefixed with a double underscore (e.g., __secret) are name-mangled to include the class name (e.g., _ClassName__secret). This provides a form of private attribute behavior. Your task is to implement a utility function get_private_attribute(obj, attr_name) that returns the attribute's value when given an object instance and the "logical" attribute name (without any leading underscores). The function should: - Return the value if the attribute exists as a normal attribute (attr_name). - If not found, try the single-underscore variant (_attr_name). - If still not found, search for name-mangled versions for every class in the instance's MRO (e.g., _ClassName__attr_name) and return the first one found (starting from the instance's class and going up the MRO). - If no matching attribute is found, return None. This exercise helps you understand how name-mangling works and how to robustly access attributes across encapsulation boundaries for debugging, testing, or serialization code.

Task

Implement get_private_attribute(obj, attr_name) that returns the value of an attribute even if it's stored as a name-mangled private attribute or a single-underscore protected attribute. Return None if not found.

Examples

Basic private attribute

Input

get_private_attribute(Vault('gold'), 'secret')

Output

gold

Vault stores its secret as __secret. Name-mangling hides it, but our helper finds _Vault__secret and returns 'gold'.

Input format

A single function call: get_private_attribute(obj, attr_name). attr_name is the attribute name without leading underscores.

Output format

Return the attribute value if found, otherwise return None.

Constraints

Do not modify the classes. The function must search: direct name, single-underscore variant, then name-mangled variants for each class in the MRO. Return None if not found.

Samples

Sample 1

Input

get_private_attribute(Note('remember'), 'note')

Output

remember

Note stores _note (single underscore). The helper checks the single-underscore variant and returns the value.