Practice: Encapsulation
Q1. Safe counter
Write class Counter with a private __count starting at 0, a method add() that increases it by 1 and a method value() that returns it. Call add twice and print value().
Goal: Use a private attribute.
Q2. Positive deposits only
Write class Wallet with balance 10. Method deposit(x) adds x only if x > 0. Deposit 5 and -3, then print balance via a get_balance method.
Goal: Validate in a method.
Q3. Age property
Create class Kid with an age property whose setter raises ValueError for negative values. Set age to 7 and print it.
Goal: Write a property.
Q4. Read-only perimeter
Write class Sq with side s stored in _s. Add a read-only property perimeter returning 4 * s. Print Sq(3).perimeter.
Goal: Computed property.
Q5. Catch invalid value
Using a Temp class whose celsius setter rejects values below -273, write code that tries to set -300 and prints 'invalid'.
Goal: Handle setter errors.
Q6. Withdraw rules
Write class Bank with private __bal = 100 and withdraw(x) that returns True and subtracts only if x <= balance, otherwise False. Print withdraw(30), withdraw(100) on separate lines.
Goal: Protect an invariant.
Q7. Private access
What does this print?
class A:
def __init__(self):
self.__x = 5
obj = A()
try:
print(obj.__x)
except AttributeError:
print("error")Goal: Name mangling effect.
Q8. Mangled name
What is printed?
class A:
def __init__(self):
self.__x = 5
obj = A()
print(obj._A__x)Goal: Read mangled names.
Q9. Protected convention
What is the output?
class B:
def __init__(self):
self._v = 9
print(B()._v)Goal: Single underscore.
Q10. Property read
What does this print?
class T:
def __init__(self):
self._n = 4
@property
def n(self):
return self._n * 2
print(T().n)Goal: Read a property.
Q11. Setter clamp
What is printed?
class L:
@property
def hp(self):
return self._hp
@hp.setter
def hp(self, v):
self._hp = max(0, v)
x = L()
x.hp = -10
print(x.hp)
x.hp = 30
print(x.hp)Goal: Trace a setter.
Q12. Read-only error
What is the output?
class R:
@property
def v(self):
return 1
try:
R().v = 2
except AttributeError:
print("read-only")Goal: Read-only properties.
Q13. Recursion bug
This property causes infinite recursion. Fix it so it prints 5.
class P:
@property
def x(self):
return self.x
@x.setter
def x(self, v):
self.x = v
p = P()
p.x = 5
print(p.x)Goal: Fix recursion.
Q14. Setter order
This code raises an error because the setter is defined before the getter. Fix it so it prints 3.
class Q:
@v.setter
def v(self, val):
self._v = val
@property
def v(self):
return self._v
q = Q()
q.v = 3
print(q.v)Goal: Fix property order.
Q15. Wrong private name
The method tries to use balance but prints an error. Fix it so it prints 50.
class A:
def __init__(self):
self.__bal = 50
def show(self):
return self.bal
print(A().show())Goal: Use the exact private name.
Q16. Is it secure?
Is a double underscore attribute truly private in Python? Explain briefly.
Goal: Understand name mangling.
Q17. Why properties?
Give two reasons to use a property instead of a plain get_ and set_ method pair.
Goal: Know why properties are Pythonic.
Q18. Health system
Application: write class Hero with a health property between 0 and 100 (setter clamps values). Set health to 150, print it, then set to -5 and print it.
Goal: Apply encapsulation.