Section 1/4The Problem with Public Data
The Problem with Public Data
If balance is public, nothing stops this:
Encapsulation
Encapsulation means bundling an object's data and the methods that operate on that data together inside a class — and then controlling access to that data. Without it, any code anywhere can corrupt your object's state.
The Problem with Public Data
If balance is public, nothing stops this:
account = BankAccount("Alice", 1000)
account.balance = -99999 # sets an impossible value
account.balance = "hello" # sets wrong type entirelyBoth lines are valid Python. The language will not stop you. Only encapsulation — controlling access through methods — can prevent this.