Problem No 1
Implement a Private Attribute in a Class
Easy≈ 8 minute session
Summary
Practice using Python's name mangling to store a private attribute and expose it safely.
Problem statement
You will implement a simple class SecretNumber that stores a numeric value as a private attribute using Python's double-underscore name mangling (e.g., __value). The class should provide a method reveal() that returns the stored number. The attribute should not be directly accessible via the obvious public attribute name (e.g., obj.value should not exist). This exercise emphasizes how to create a private attribute and access it from within the class.
Task
Create a class that stores a value in a truly private attribute (using double-underscore name mangling) and provide a method that exposes the stored value.
Examples
Store and reveal a secret number
Input
SecretNumber(42).reveal()
Output
42
Explanation
The number 42 is stored in a private attribute and revealed through the reveal() method.
Input format
A single expression that creates a SecretNumber and calls its reveal() method or inspects attributes (evaluated by the test runner).
Output format
Return the numeric value (or a boolean for attribute-existence checks). The test harness converts the result to string for comparison.
Constraints
Use double-leading-underscore (name mangling) for the private attribute. Do not expose the value as a public attribute named 'value'.
Samples
Sample input 0
SecretNumber(7).reveal()
Sample output 0
7
Explanation 0
SecretNumber stores 7 privately and reveal() returns it.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.