Understanding Encapsulation Using Examples
Get a firmer understanding of encapsulation in Python with the help of examples.
We'll cover the following
Encapsulation refers to the concept of binding data and the methods operating on that data in a single unit, which is also called a class.
The goal is to prevent this bound data from any unwanted access by the code outside this class. Let’s understand this by using an example of a very basic User
class.
Consider that we are up for designing an application and are working on modeling the log in part of that application. We know that a user needs a username and a password to log into the application.
An elementary User
class will be modeled as:
- Having a property
userName
- Having a property
password
- A method named
login()
to grant access
Whenever a new user comes, a new object can be created by passing the userName
and password
to the constructor of this class.
Get hands-on with 1200+ tech skills courses.