Practice: Encapsulation

« Read the chapter

Q1. Safe counter

BeginnerCoding

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

BeginnerCoding

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

IntermediateCoding

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

IntermediateCoding

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

IntermediateCoding

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

AdvancedCoding

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

BeginnerOutput

What does this print?

Code
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

IntermediateOutput

What is printed?

Code
class A:
    def __init__(self):
        self.__x = 5
obj = A()
print(obj._A__x)

Goal: Read mangled names.

Q9. Protected convention

BeginnerOutput

What is the output?

Code
class B:
    def __init__(self):
        self._v = 9
print(B()._v)

Goal: Single underscore.

Q10. Property read

IntermediateOutput

What does this print?

Code
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

AdvancedOutput

What is printed?

Code
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

IntermediateOutput

What is the output?

Code
class R:
    @property
    def v(self):
        return 1
try:
    R().v = 2
except AttributeError:
    print("read-only")

Goal: Read-only properties.

Q13. Recursion bug

AdvancedDebugging

This property causes infinite recursion. Fix it so it prints 5.

Code
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

IntermediateDebugging

This code raises an error because the setter is defined before the getter. Fix it so it prints 3.

Code
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

BeginnerDebugging

The method tries to use balance but prints an error. Fix it so it prints 50.

Code
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?

BeginnerConceptual

Is a double underscore attribute truly private in Python? Explain briefly.

Goal: Understand name mangling.

Q17. Why properties?

IntermediateConceptual

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

AdvancedApplication

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.