Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Protect Internal State with Name Mangling

Learn to keep an object's internal state private using Python's name mangling (double-underscore) and expose a safe public API.

Python practice24 minEncapsulation & Access PatternsAdvancedLast updated April 8, 2026

Problem statement

You will implement a SecureCounter class that keeps its numeric state hidden using Python's name mangling (a double-underscore attribute like __count). The class should provide safe methods to increment, decrement (never allowing the counter to go below zero), read the value via a property, and transfer an amount to another SecureCounter. The goal is to practice encapsulation: the internal state must be stored in a name-mangled attribute and not exposed as a plain public attribute.

Task

Implement a class that uses a name-mangled attribute to store internal state, and provide controlled read/write operations through methods and properties.

Examples

Basic usage

Input

c = SecureCounter(3) c.increment() c.value

Output

4

Create a counter starting at 3, increment by 1 (default) and read the value property which returns 4.

Input format

You will construct and call methods on the SecureCounter class. Examples: SecureCounter(5).increment(), SecureCounter(2).decrement(1), etc.

Output format

Return values from method calls or the value property. The tests compare the string form of the returned value.

Constraints

Do not expose the internal numeric state as a public attribute. Store it using a name-mangled attribute (e.g. self.__count). decrement must clamp at 0 (never negative). Methods should return sensible values: increment/decrement return the new integer value; value is a read-only property; transfer_to modifies both counters.

Samples

Sample 1

Input

SecureCounter(3).increment()

Output

4

Incrementing a counter starting at 3 by the default 1 returns 4.