Summary - Encapsulation
- Python course
- Intermediate
- Lesson 23/116
- 5 min
Combine @property, @dataclass and __slots__ to write an Account class.
Summary - Encapsulation
In this group we covered encapsulation: the _balance convention, a getter with @property, a setter with @x.setter, lean classes with @dataclass and layout limits with __slots__.
Encapsulation protects inner data and keeps the outer interface stable. @property + a setter validate during assignment. @dataclass simplifies boilerplate. __slots__ gives memory and layout control. Now we'll combine these into an Account class.
Practice Combine the Account class
Define the Account class. Add __init__(self, balance) with self._balance = balance. Add @property with def balance(self): and return self._balance. Add @balance.setter with def balance(self, value):; in the body write if value < 0: and return, then self._balance = value. Then call a = Account(100) and print(a.balance).
Starter code
# Combine the Account classSample solution
# Combine the Account class
class Account:
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
return
self._balance = value
a = Account(100)
print(a.balance)Expected output
100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is done inside a setter?
- The class is deleted
- A new instance is created
- The assigned value is validated and written to inner data Correct answer
- The class name is changed
Explanation: The setter validates the value and writes it to the inner attribute.
2 Match the concepts
| Term | Meaning |
|---|---|
_balance |
Private attribute |
@property |
Getter |
@balance.setter |
Setter |
3 Complete the getter body
@property
def balance(self):
return self.____
@property
def balance(self):
return self._balance
Explanation: The getter returns the inner _balance attribute.