Encapsulation Practice
Hide data using private members and expose it through getters and setters.
1
Private Attribute — Double Underscore
Easy
Write a class Person with a private attribute __age. Set it to the input value and print it inside a method get_age().
Input Format
A single line containing the age.
Output Format
Print the age.
Sample Test Cases
|
Sample Input 1
25 |
Sample Output 1
25 |
|
Sample Input 2
30 |
Sample Output 2
30 |
|
Sample Input 3
0 |
Sample Output 3
0 |
2
Getter Method for Private Data
Easy
Write a class Account with a private attribute __balance = 1000 and a method get_balance() that returns it.
Input Format
No input.
Output Format
Print the balance.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
1000 |
|
Sample Input 2
|
Sample Output 2
1000 |
|
Sample Input 3
|
Sample Output 3
1000 |
3
Name Mangling Access
Easy
Write a class Demo with private attribute __secret = 'hidden'. Access it using name mangling _Demo__secret and print it.
Input Format
No input.
Output Format
Print the secret value.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
hidden |
|
Sample Input 2
|
Sample Output 2
hidden |
|
Sample Input 3
|
Sample Output 3
hidden |
4
Setter Method
Easy
Write a class Student with private __marks and a method set_marks(m) to set it. Set it to the input and print via getter.
Input Format
A single line containing the marks.
Output Format
Print the marks.
Sample Test Cases
|
Sample Input 1
85 |
Sample Output 1
85 |
|
Sample Input 2
99 |
Sample Output 2
99 |
|
Sample Input 3
0 |
Sample Output 3
0 |
5
Protected Attribute Convention
Easy
Write a class Employee with a protected attribute _salary (single underscore). Set it to the input and print it inside the class.
Input Format
A single line containing the salary.
Output Format
Print the salary.
Sample Test Cases
|
Sample Input 1
40000 |
Sample Output 1
40000 |
|
Sample Input 2
100000 |
Sample Output 2
100000 |
|
Sample Input 3
0 |
Sample Output 3
0 |
6
Private Attribute with Method
Easy
Write a class BankAccount with private __pin = 1234 and a method check_pin(pin) that returns True if it matches.
Input Format
A single line containing the pin attempt.
Output Format
Print True or False.
Sample Test Cases
|
Sample Input 1
1234 |
Sample Output 1
True |
|
Sample Input 2
0000 |
Sample Output 2
False |
|
Sample Input 3
1234 |
Sample Output 3
True |
7
Encapsulated Counter
Easy
Write a class Counter with private __count = 0 and a method increment() that increases it by 1. Call it once and print the count.
Input Format
No input.
Output Format
Print 1.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
1 |
|
Sample Input 2
|
Sample Output 2
1 |
|
Sample Input 3
|
Sample Output 3
1 |
8
Read-Only Private Attribute
Easy
Write a class Temperature with private __value set by input and only a getter (no setter). Read the value, print it.
Input Format
A single line containing the temperature.
Output Format
Print the temperature.
Sample Test Cases
|
Sample Input 1
36.6 |
Sample Output 1
36.6 |
|
Sample Input 2
0 |
Sample Output 2
0 |
|
Sample Input 3
-10 |
Sample Output 3
-10 |
9
Private List Attribute
Easy
Write a class ToDoList with private __tasks = [] and a method add(task) to append. Add one task and print the list via a getter.
Input Format
A single line containing a task.
Output Format
Print the list of tasks.
Sample Test Cases
|
Sample Input 1
Study Python |
Sample Output 1
['Study Python'] |
|
Sample Input 2
Buy milk |
Sample Output 2
['Buy milk'] |
|
Sample Input 3
Clean |
Sample Output 3
['Clean'] |
10
Data Hiding with Display
Easy
Write a class Password with private __password and a method show() that prints 'Password is hidden'.
Input Format
No input.
Output Format
Print 'Password is hidden'.
Sample Test Cases
|
Sample Input 1
|
Sample Output 1
Password is hidden |
|
Sample Input 2
|
Sample Output 2
Password is hidden |
|
Sample Input 3
|
Sample Output 3
Password is hidden |
1
Getters and Setters for Multiple Fields
Medium
Write a class Employee with private __name and __salary and getters/setters for both.
Input Format
First line: name. Second line: salary.
Output Format
Print name and salary after setting them.
Sample Test Cases
|
Sample Input 1
Alice 50000 |
Sample Output 1
Alice 50000 |
|
Sample Input 2
Bob 60000 |
Sample Output 2
Bob 60000 |
|
Sample Input 3
Sam 10000 |
Sample Output 3
Sam 10000 |
2
Validation in Setter
Medium
Write a class Student with a setter for __marks that rejects values below 0 or above 100 by printing 'Invalid marks'.
Input Format
A single line containing the marks.
Output Format
Print the marks, or 'Invalid marks'.
Sample Test Cases
|
Sample Input 1
150 |
Sample Output 1
Invalid marks |
|
Sample Input 2
50 |
Sample Output 2
50 |
|
Sample Input 3
-1 |
Sample Output 3
Invalid marks |
3
Private Counter with Reset
Medium
Write a class Counter with private __count and methods increment(), reset(), and get_count().
Input Format
First line: number of increments. Second line: 1 if reset should happen before printing, else 0.
Output Format
Print the count after the operation.
Sample Test Cases
|
Sample Input 1
5 1 |
Sample Output 1
0 |
|
Sample Input 2
3 0 |
Sample Output 2
3 |
|
Sample Input 3
0 1 |
Sample Output 3
0 |
4
Encapsulated Bank Account
Medium
Write a class BankAccount with private __balance and methods deposit(amount) and get_balance(). Deposits below 1 print 'Invalid amount'.
Input Format
A single line containing the deposit amount.
Output Format
Print the balance, or 'Invalid amount'.
Sample Test Cases
|
Sample Input 1
0 |
Sample Output 1
Invalid amount |
|
Sample Input 2
50 |
Sample Output 2
50 |
|
Sample Input 3
-5 |
Sample Output 3
Invalid amount |
5
Property Decorator — Getter
Medium
Write a class Circle with private __radius and a @property radius getter that returns it.
Input Format
A single line containing the radius.
Output Format
Print the radius.
Sample Test Cases
|
Sample Input 1
7 |
Sample Output 1
7 |
|
Sample Input 2
1 |
Sample Output 2
1 |
|
Sample Input 3
9 |
Sample Output 3
9 |
6
Property Decorator — Setter with Validation
Medium
Write a class Person with private __age and a @property with a setter that rejects negative age by printing 'Invalid age'.
Input Format
A single line containing the age.
Output Format
Print the age, or 'Invalid age'.
Sample Test Cases
|
Sample Input 1
-5 |
Sample Output 1
Invalid age |
|
Sample Input 2
25 |
Sample Output 2
25 |
|
Sample Input 3
-1 |
Sample Output 3
Invalid age |
7
Data Hiding in Bank Transfer
Medium
Write a class Account with private __balance and a method transfer(other, amount) that only works if the balance is sufficient.
Input Format
First line: balance of A. Second line: balance of B. Third line: amount.
Output Format
Print 'Transfer successful' or 'Insufficient balance', then both balances.
Sample Test Cases
|
Sample Input 1
1000 500 300 |
Sample Output 1
Transfer successful A: 700 B: 800 |
|
Sample Input 2
100 0 50 |
Sample Output 2
Transfer successful A: 50 B: 50 |
|
Sample Input 3
10 0 20 |
Sample Output 3
Insufficient balance |
8
Getter Computes Derived Value
Medium
Write a class Rectangle with private __length and __breadth, and a getter area() that computes and returns the area.
Input Format
A single line containing two space-separated integers.
Output Format
Print the area.
Sample Test Cases
|
Sample Input 1
4 5 |
Sample Output 1
20 |
|
Sample Input 2
2 8 |
Sample Output 2
16 |
|
Sample Input 3
10 10 |
Sample Output 3
100 |
9
Encapsulation with __str__
Medium
Write a class Student with private __name and __grade, and a __str__ method that returns 'name - grade'.
Input Format
First line: name. Second line: grade.
Output Format
Print the string representation.
Sample Test Cases
|
Sample Input 1
Alice A |
Sample Output 1
Alice - A |
|
Sample Input 2
Bob B |
Sample Output 2
Bob - B |
|
Sample Input 3
Sam C |
Sample Output 3
Sam - C |
10
Protected Member in Derived Class
Medium
Write a base class Vehicle with protected attribute _speed, and a derived class Car that accesses it and prints it.
Input Format
A single line containing the speed.
Output Format
Print the speed.
Sample Test Cases
|
Sample Input 1
80 |
Sample Output 1
80 |
|
Sample Input 2
120 |
Sample Output 2
120 |
|
Sample Input 3
0 |
Sample Output 3
0 |
1
Full Encapsulation — ATM Simulation
Hard
Write a class ATM with private __balance and __pin, methods authenticate(pin), deposit(amount), and withdraw(amount).
Input Format
First line: initial balance. Second line: correct pin. Third line: pin attempt. Fourth line: deposit. Fifth line: withdrawal.
Output Format
Print 'Authenticated' or 'Wrong pin', then the final balance.
Sample Test Cases
|
Sample Input 1
5000 1234 1234 1000 1500 |
Sample Output 1
Authenticated 4500 |
|
Sample Input 2
1000 1111 0000 100 200 |
Sample Output 2
Wrong pin 1200 |
|
Sample Input 3
1000 1234 1234 0 0 |
Sample Output 3
Authenticated 1000 |
2
Encapsulated Shopping Cart
Hard
Write a class Cart with private __items dict and methods add(item, qty), remove(item), and total_items().
Input Format
Multiple lines: item and qty space-separated. End with empty line.
Output Format
Print the total items in the cart.
Sample Test Cases
|
Sample Input 1
apple 3 banana 2 mango 5 |
Sample Output 1
10 |
|
Sample Input 2
x 1 y 2 |
Sample Output 2
3 |
|
Sample Input 3
a 10 a 20 |
Sample Output 3
30 |
3
Property with Private Storage
Hard
Write a class Temperature with private __celsius, a @property celsius, and a @property fahrenheit computed as c * 9/5 + 32.
Input Format
A single line containing the celsius value.
Output Format
Print the fahrenheit value rounded to 2 decimal places.
Sample Test Cases
|
Sample Input 1
100 |
Sample Output 1
212.00 |
|
Sample Input 2
0 |
Sample Output 2
32.00 |
|
Sample Input 3
37 |
Sample Output 3
98.60 |
4
Encapsulated Employee with Salary Rules
Hard
Write a class Employee with private __salary and a setter that applies a 10% bonus automatically.
Input Format
A single line containing the base salary.
Output Format
Print the salary after bonus.
Sample Test Cases
|
Sample Input 1
50000 |
Sample Output 1
55000.0 |
|
Sample Input 2
1000 |
Sample Output 2
1100.0 |
|
Sample Input 3
0 |
Sample Output 3
0.0 |
5
Bank Account with Transaction Log
Hard
Write a class BankAccount with private __balance and private __log list. Methods deposit/withdraw append to the log.
Input Format
First line: initial balance. Second line: deposit. Third line: withdrawal.
Output Format
Print the final balance and the transaction log.
Sample Test Cases
|
Sample Input 1
1000 500 200 |
Sample Output 1
1300 ['deposit 500', 'withdraw 200'] |
|
Sample Input 2
100 100 50 |
Sample Output 2
150 ['deposit 100', 'withdraw 50'] |
|
Sample Input 3
0 0 0 |
Sample Output 3
0 [] |
6
Password Manager with Validation
Hard
Write a class PasswordManager with private __password and a setter that only accepts passwords of length ≥ 8, else prints 'Too short'.
Input Format
A single line containing a password.
Output Format
Print 'Password set' or 'Too short'.
Sample Test Cases
|
Sample Input 1
abc |
Sample Output 1
Too short |
|
Sample Input 2
12345678 |
Sample Output 2
Password set |
|
Sample Input 3
1234567 |
Sample Output 3
Too short |
7
Encapsulated Stack
Hard
Write a class Stack with private __items and methods push(x), pop(), and peek().
Input Format
First line: elements to push space-separated. Second line: 1 to pop once, else 0.
Output Format
Print the stack after the operation.
Sample Test Cases
|
Sample Input 1
1 2 3 1 |
Sample Output 1
[1, 2] |
|
Sample Input 2
1 2 3 0 |
Sample Output 2
[1, 2, 3] |
|
Sample Input 3
5 1 |
Sample Output 3
[] |
8
Student Grades with Average
Hard
Write a class Student with private __marks list, add_mark(m) with validation (0-100), and get_average().
Input Format
A single line containing three space-separated marks.
Output Format
Print the average rounded to 2 decimal places.
Sample Test Cases
|
Sample Input 1
80 90 70 |
Sample Output 1
80.00 |
|
Sample Input 2
100 90 80 |
Sample Output 2
90.00 |
|
Sample Input 3
10 20 30 |
Sample Output 3
20.00 |
9
Bank with Interest Encapsulation
Hard
Write a class Account with private __balance and private __rate, with a method apply_interest() that adds rate% to balance.
Input Format
First line: initial balance. Second line: interest rate.
Output Format
Print the balance after interest rounded to 2 decimal places.
Sample Test Cases
|
Sample Input 1
20000 6.5 |
Sample Output 1
21300.00 |
|
Sample Input 2
1000 10 |
Sample Output 2
1100.00 |
|
Sample Input 3
0 5 |
Sample Output 3
0.00 |
10
Multi-Account Encapsulation
Hard
Write a class Bank that holds private dict of accounts and methods create(name, balance), deposit(name, amt), and balance(name).
Input Format
Multiple lines: operation and arguments space-separated. End with empty line.
Output Format
Print the result of each query line.
Sample Test Cases
|
Sample Input 1
create Alice 5000 deposit Alice 1000 balance Alice |
Sample Output 1
15000 6000 6000 |
|
Sample Input 2
create A 100 balance A |
Sample Output 2
500 100 100 |
|
Sample Input 3
balance X |
Sample Output 3
0 0 0 |
Competitive MCQs — Encapsulation
Code snippets, output prediction, concepts & error spotting. Pick an answer to see instant feedback.
Score
0/ 39
Q1
What does encapsulation primarily provide?
Correct!
Wrong — correct answer is .
Encapsulation hides state and exposes controlled access via methods.
Q2
How do you indicate a "private" attribute by convention in Python?
Correct!
Wrong — correct answer is .
A leading underscore signals internal use by convention.
Q3
What is the output of this code?
class A:
def __init__(self):
self.__x = 1
def set_x(self, v):
if v > 0:
self.__x = v
a = A()
a.set_x(-5)
print(a._A__x)
class A:
def __init__(self):
self.__x = 1
def set_x(self, v):
if v > 0:
self.__x = v
a = A()
a.set_x(-5)
print(a._A__x)
Correct!
Wrong — correct answer is .
The setter rejects -5, so the stored value stays 1.
Q4
What is the output of this code?
python
1
2
3
4
5
2
3
4
5
class A:
def __init__(self):
self._x = 10
a = A()
print(a._x)Correct!
Wrong — correct answer is .
The underscore is only a convention — the attribute is still accessible.
Q5
What is the purpose of a getter?
Correct!
Wrong — correct answer is .
Getters expose values without granting direct write access.
Q6
Which of these is a getter-style method?
Correct!
Wrong — correct answer is .
A getter is a normal method (by convention named get_xxx) returning a field.
Q7
What is the purpose of a setter?
Correct!
Wrong — correct answer is .
Setters intercept changes and can enforce rules.
Q8
What is name mangling for __attr (double underscore)?
Correct!
Wrong — correct answer is .
Double-underscore names are mangled to _ClassName__attr inside the class.
Q9
What is the output of this code?
class A:
def __init__(self):
self.__n = 2
def get_n(self):
return self.__n
a = A()
print(a.get_n())
class A:
def __init__(self):
self.__n = 2
def get_n(self):
return self.__n
a = A()
print(a.get_n())
Correct!
Wrong — correct answer is .
The getter returns the mangled private value 2.
Q10
What is the output of this code?
python
1
2
3
4
5
2
3
4
5
class A:
def __init__(self):
self.__x = 5
a = A()
print(a._A__x)Correct!
Wrong — correct answer is .
Name mangling stores it as _A__x, so this accesses the value 5.
Q11
Which statement about _single underscore is TRUE?
Correct!
Wrong — correct answer is .
A single underscore signals "internal use" but remains reachable.
Q12
Which tool turns a method into a managed attribute?
Correct!
Wrong — correct answer is .
@property lets a method be read like an attribute, with logic behind it.
Q13
What is the output of this code?
class A:
def __init__(self):
self.__x = 3
print(A().__dict__)
class A:
def __init__(self):
self.__x = 3
print(A().__dict__)
Correct!
Wrong — correct answer is .
Name mangling renames __x to _A__x in the instance dictionary.
Q14
What is the main benefit of private fields with getters/setters?
Correct!
Wrong — correct answer is .
Setters can validate inputs before changing internal state.
Q15
Which method turns a getter into an attribute-like access?
Correct!
Wrong — correct answer is .
Decorating a method with @property lets you read obj.attr without parentheses.
Q16
What is the output of this code?
python
1
2
3
4
5
6
7
2
3
4
5
6
7
class Bank:
def __init__(self):
self.__balance = 100
def get_balance(self):
return self.__balance
b = Bank()
print(b.get_balance())Correct!
Wrong — correct answer is .
The getter returns the mangled private balance, 100.
Q17
What is the output of this code?
class A:
@property
def val(self):
return 42
print(A().val)
class A:
@property
def val(self):
return 42
print(A().val)
Correct!
Wrong — correct answer is .
val is a property, so reading it calls the method and returns 42.
Q18
Why is direct access to internals discouraged?
Correct!
Wrong — correct answer is .
Controlled access prevents callers from corrupting object state.
Q19
What is information hiding?
Correct!
Wrong — correct answer is .
Information hiding is the core of encapsulation.
Q20
Which of these is an example of encapsulation?
Correct!
Wrong — correct answer is .
Encapsulated objects expose controlled operations instead of raw state.
Q21
What is the output of this code?
class A:
def __init__(self):
self._x = 5
def get_x(self):
return self._x
a = A()
print(a._x)
class A:
def __init__(self):
self._x = 5
def get_x(self):
return self._x
a = A()
print(a._x)
Correct!
Wrong — correct answer is .
A single underscore does not block access; the value is 5.
Q22
Which is the best practice for validating a new age?
Correct!
Wrong — correct answer is .
Setters enforce invariants before state changes.
Q23
What is the output of this code?
class A:
def __init__(self):
self.__items = []
def add(self, v):
self.__items.append(v)
a = A()
a.add(1)
print(len(a._A__items))
class A:
def __init__(self):
self.__items = []
def add(self, v):
self.__items.append(v)
a = A()
a.add(1)
print(len(a._A__items))
Correct!
Wrong — correct answer is .
add() appends to the mangled list, whose length becomes 1.
Q24
Why use properties instead of plain attributes?
Correct!
Wrong — correct answer is .
Properties keep the public interface stable while adding behavior.
Q25
Which of the following best hides implementation details?
Correct!
Wrong — correct answer is .
Encapsulation exposes operations while hiding the underlying data.
Q26
What is the output of this code?
class A:
def __init__(self):
self.__x = 10
def set_x(self, v):
if v >= 0:
self.__x = v
a = A()
a.set_x(20)
print(a._A__x)
class A:
def __init__(self):
self.__x = 10
def set_x(self, v):
if v >= 0:
self.__x = v
a = A()
a.set_x(20)
print(a._A__x)
Correct!
Wrong — correct answer is .
The setter accepts 20 and updates the private value.
Q27
Which naming convention signals "protected" in Python?
Correct!
Wrong — correct answer is .
_x is the conventional protected marker for subclass use.
Q28
What is a downside of making every attribute public?
Correct!
Wrong — correct answer is .
Public internals couple callers to details that may change.
Q29
What is the output of this code?
class A:
def __init__(self):
self._secret = "s3cret"
a = A()
print(a._secret)
class A:
def __init__(self):
self._secret = "s3cret"
a = A()
print(a._secret)
Correct!
Wrong — correct answer is .
The underscore is a warning, not a barrier — access still works.
Q30
What does a property setter method look like?
Correct!
Wrong — correct answer is .
The setter uses @property-name.setter above a same-named method.
Q31
What is the output of this code?
class A:
def __init__(self):
self.__x = 4
@property
def x(self):
return self.__x
@x.setter
def x(self, v):
if v > 0:
self.__x = v
a = A()
a.x = 9
print(a.x)
class A:
def __init__(self):
self.__x = 4
@property
def x(self):
return self.__x
@x.setter
def x(self, v):
if v > 0:
self.__x = v
a = A()
a.x = 9
print(a.x)
Correct!
Wrong — correct answer is .
The setter accepts 9 and the property getter returns it.
Q32
Which of these is a private-by-convention attribute?
Correct!
Wrong — correct answer is .
A single leading underscore signals the attribute is internal.
Q33
What is the output of this code?
class A:
def __init__(self):
self._x = 5
def get_x(self):
return self._x + 1
a = A()
print(a.get_x())
class A:
def __init__(self):
self._x = 5
def get_x(self):
return self._x + 1
a = A()
print(a.get_x())
Correct!
Wrong — correct answer is .
The getter returns the stored 5 plus 1, giving 6.
Q34
What happens when you access a mangled attribute directly from outside?
Correct!
Wrong — correct answer is .
Only the mangled name exists, so the plain name fails with AttributeError.
Q35
Why are setters useful for validation?
Correct!
Wrong — correct answer is .
Validation in setters keeps objects in a valid state.
Q36
What is the output of this code?
class A:
def __init__(self):
self.__x = 1
def inc(self):
self.__x += 1
return self.__x
a = A()
print(a.inc(), a.inc())
class A:
def __init__(self):
self.__x = 1
def inc(self):
self.__x += 1
return self.__x
a = A()
print(a.inc(), a.inc())
Correct!
Wrong — correct answer is .
Each inc() raises the private counter: first to 2, then 3.
Q37
Which of the following best represents encapsulation?
Correct!
Wrong — correct answer is .
Encapsulation wraps state with controlled operations.
Q38
What is the output of this code?
class A:
def __init__(self):
self.__x = 10
print(A().__dict__["_A__x"])
class A:
def __init__(self):
self.__x = 10
print(A().__dict__["_A__x"])
Correct!
Wrong — correct answer is .
The mangled key holds 10, retrievable through the instance dict.
Q39
What does the underscore prefix signal to other developers?
Correct!
Wrong — correct answer is .
Leading underscores communicate intent about internal use.