Welcome to this tutorial! Our goal is to understand the concept of encapsulation and data protection in Python. Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It’s a protective barrier that prevents the data from being accessed directly.
By the end of the tutorial, you will learn:
- What is encapsulation and data protection
- Why encapsulation is important
- How to implement encapsulation in Python
Prerequisites: Basic knowledge of Python and understanding of Object-Oriented Programming (OOP) concepts.
Encapsulation is an OOP principle that binds together the data and functions that manipulate the data and keeps them safe from outside interference and misuse. Data encapsulation leads to the important OOP concept of data hiding.
Encapsulation protects the data from accidental modification, but the data is still accessible if necessary. It provides a way to control and validate whatever data is going to be set or get.
In Python, encapsulation is achieved by declaring private attributes or methods using an underscore (_). A double underscore (__) makes them private to their class, they can't be accessed directly outside of it.
Here is a simple example of encapsulation:
class Car:
def __init__(self):
self.__maxspeed = 200 # private attribute
def drive(self):
print('Driving. Max speed is', self.__maxspeed)
redcar = Car()
redcar.drive()
This will output:
Driving. Max speed is 200
In this example, __maxspeed
is a private member of the class Car. If you try to access it directly, Python will raise an error.
In this tutorial, we've covered the following key points:
To continue improving your Python OOP skills, we recommend practicing encapsulation and other OOP principles with more complex examples and projects.
Here are some exercises for you to practice:
Create a class BankAccount
with a private attribute __balance
. Add methods to deposit and withdraw money, and make sure you can't withdraw more money than the balance.
Create a class Person
with private attributes __name
and __age
. Add methods to set and get these attributes, ensuring that the name must be a string and age must be a positive integer.
Solutions:
class BankAccount:
def __init__(self):
self.__balance = 0
def deposit(self, amount):
self.__balance += amount
return self.__balance
def withdraw(self, amount):
if amount > self.__balance:
print("Insufficient balance!")
return
self.__balance -= amount
return self.__balance
class Person:
def __init__(self):
self.__name = ''
self.__age = 0
def set_name(self, name):
if not isinstance(name, str):
print("Name must be a string!")
return
self.__name = name
def set_age(self, age):
if not isinstance(age, int) or age < 0:
print("Age must be a positive integer!")
return
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
Keep practicing and happy coding!