OOP – Private Attributes (underscore convention), online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
OOP – Private Attributes (underscore convention) in one minute
What students need to know
A single underscore is a convention meaning 'do not access directly'. Getters provide controlled read access to private attributes.
_name signals 'treat this as private' — Python won't stop you accessing it though. __name becomes _ClassName__name — Python mangles it to make accidental access harder.
Mistakes students make
- Directly setting _balance bypasses validation. Use deposit() method.
- __balance is name-mangled. Access through a getter method.
- No validation should reject negative deposits.
- Setter has no validation should check age > 0.
PREVIOUS · MODULE 54OOP – Class Variables vs Instance Variables
YOU ARE HERE · MODULE 55OOP – Private Attributes (underscore convention)
NEXT · MODULE 56OOP – Inheritance (basic)
What students will learn in this module
Every question in Module 55
Quick questions
- What does a single underscore _ prefix mean?AConvention: internal use, don't access directlyBThe variable is deleted
- Does Python enforce single-underscore privacy?AYes you can't access itBNo it's just a convention
- What does double underscore __ do?ADeletes the variableBName mangling makes it harder to access
- Why use getters and setters?ATo control and validate access to attributesBThey're faster
- def get_balance(self): what is this?AA getter method that returns the balanceBA constructor
Key terms
Students type the meaning of:
_variable__variableGetterSetter
Match the pairs
obj.__balanceMatch it to what it doesdef getBalance(self):Match it to what it doesself._balanceMatch it to what it doesdef get_balance(self):Match it to what it does10 // 3Match it to what it does10 % 3Match it to what it doesFill in the blanks
class Account: def ________(self, bal): self._balance = balclass Account: def get_balance(____): return self._balanceclass Account: def deposit(self, amount): if amount _ 0: self.________ += amountclass Secret: def ________(self, val): self.__val = valacc = Account(100) print(acc.___________( ))
Spot the error
Question 1
Aacc = BankAccount(100)Bacc._balance = -500Cprint(acc.get_balance())
Question 2
Aclass Account:B def __init__(self, bal):C self.__balance = balDEacc = Account(100)Fprint(acc.__balance)
Question 3
Aclass Account:B def deposit(self, amount):C self._balance += amount
Question 4
Aclass Person:B def __init__(self, age):C self._age = ageD def set_age(self, age):E self._age = age
Question 5
Aclass Account:B def __init__(self, bal):C self._balance = balD def get_balance():E return self._balance
