8.6 Encapsulation
Learning encapsulation to protect an object's data, using conventions for public, protected (_), and private (__) attributes, as well as getters/setters with @property.
Encapsulation is the principle of bundling data (attributes) and the methods that handle them into a single unit (the class). An important part of encapsulation is hiding the internal state of an object (data hiding) from direct external access, exposing only a controlled way of interaction through public methods. This protects the data from accidental or invalid modifications.
In Python, there is no strict private access control as in other languages (e.g., Java). Instead, naming conventions are used: a single underscore (`_`) indicates that an attribute is "protected" (for internal use), while two underscores (`__`) cause "name mangling" to make the attribute "private" (harder to access from outside).
class BankAccount:
def __init__(self, initial_balance):
self.__balance = initial_balance # "Private"
def display_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
account = BankAccount(1000)
account.deposit(200)
# You cannot do account.__balance = 5000 directly
print(f"Balance: {account.display_balance()}€")
Practical Exercises
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.