Encapsulation in Python

By Rahul Lath on Apr 19, 2023

Updated Jan 30, 2025

encapsulation in python

Find top-rated tutors

Popular

subject

Singing

subject

Math

subject

English

subject

Spanish

subject

Guitar

subject

Piano

subject

Algebra

subject

Calculus

subject

Physics

subject

Chemistry

subject

Biology

subject

AP Calculus

subject

SAT Test

subject

ACT Test

subject

Economics

subject

ESL

subject

Coding

subject

French

subject

Python

subject

Electrical Engineering

subject

Java

subject

Electronics Engineering

subject

Revit

subject

Organic Chemistry

Victoria Frisher - Singing tutor

Dynamic Singing Tutor with over 9 years of experience and a Master’s in Music specializing in pop vocals. I’ve worked with 200+ students, offering personalized, hands-on lessons that bring out your best. Let’s develop your voice and boost your confidence together!

Hello, I'm Victoria Frisher, I'm a professional singing tutor and singer. With a Masters degree in Music and professional qualifications as a pop lead vocalist, ensemble vocalist, voice teacher in higher education, and music arts manager. I've been working as a vocal participant of many cover projects, backing vocalist and vocal teacher. I have over 15 years of performing practice, extensive studio work and more than 9 years of teaching experience. I bring a wealth of experience to my teaching. My teaching philosophy revolves around creating a supportive and nurturing environment where students feel motivated to explore their musical abilities. I believe in tailoring my approach to suit each student's learning style and pace, ensuring personalized attention and growth. I engage students by incorporating a mix of modern and traditional vocal techniques, modern music trends, and interactive learning activities. By making lessons fun and interactive, I aim to inspire a love for music and build confidence in my students at all levels. I am excited to share my passion for music with you and help you reach your full potential as a singer. Let's embark on this musical journey together!

Free trial lesson

4.8

(85)

$30

/ hour

Super Tutor

Karine Longis McMillan - English tutor

Experienced English Tutor with 15+ Years of Experience and a Doctorate in Psychology in Education. Interactive, Creative, and Practical Lessons to Enhance Problem-Solving Skills. Join 200+ Students in Engaging Hands-On Learning at University of Toulouse Graduate!

Hello! I'm Karine Longis McMillan, a Doctorate degree holder specializing in Psychology in Education from France. I also have a Teaching degree from Ireland and a Masters in Eduction from England. With a passion for teaching English, I offer tutoring in ESL, IELTS, and English for students of all levels. I currently reside in France with my family. I have been teaching for over 16 years and I love what I do. I have worked on different continents and with people of different age and from different professional background. My teaching philosophy centers around creating a supportive and engaging learning environment where students feel motivated to excel. I believe in personalized learning to cater to individual needs and learning styles. Through interactive and practical lessons, I aim to enhance not only language skills but also critical thinking and communication abilities. Let's embark on a journey of language learning together! We can talk about daily activities, travelling or focus more a professional approach. You tell me what you need and I work to help you achieve your goals without any kind of stress on your parts. I am also very flexible in the hours I work. So do not hesitate to contact me!

Free trial lesson

4.8

(113)

$40

$32

/ hour

Super Tutor

Emily Shaull - Singing tutor

Unleash Your Voice with a Seasoned Singing Tutor! 5+ Years of Experience Providing Engaging, Creative, and Supportive Lessons to 10+ Students. Discover Your Unique Style and Flourish in Music!

Hello, fellow musician! My name is Emily Shaull, and I would love to teach you! I am a caring, creative, and supportive Music tutor who will challenge you to take your musical skills to the next level! I've always loved to sing. My musical journey began at a very young age when I began taking piano lessons with my grandmother. As I grew, I became increasingly involved with music through a number of various avenues-- musical theater, choir, leading musical and religious events, private piano and voice lessons, marching band, and symphonic band! One of my highlights of my younger years was to tour professionally in parts of Europe. I was able to work with some incredible instructors. They are a huge part of why I chose to go into the Music field. So why else did I choose to teach music? 1. People. I love people! One of my passions is to invest into others and healthily challenge them to grow in their giftings. 2. Let's face it--I'm a huge music theory nerd. I was actually a Teacher's Assistant during college for Music Theory! 3. Music is an ART. It is one that sets my heart on fire and makes me dance inside. I love how music can show such deep expression and tell intricate stories to its listeners. 4. Singing is like breathing to me. It is something I truly love. I also am in awe of how our amazing bodies can make such a wide breadth of beautiful sounds! We ourselves are instruments. So there you have it! Music is basically my life. Would you like me to help you to make it an even more wonderful part of yours as well? (:

Free trial lesson

4.7

(67)

$33

$24

/ hour

Student Favourite

Show all

What is Encapsulation in Python?

Encapsulation, which is the practice of obscuring data or implementation details within a class, is one of the fundamental concepts of object-oriented programming (OOP). This method combines the methods that act on the data with the data itself into a single unit. This enables the creation of objects with a predetermined set of attributes and behaviors that can be accessed and changed in a controlled way.

Encapsulation is a technique for hiding a class’ internal operations and exposing only the information required for external interactions. It enables the creation of objects with clearly defined behaviors and properties, enhancing their usability and security. Encapsulation restricts access to a class’s data to its methods and keeps the class’s variables private.

Reasons to use encapsulation in python:

  • Only the necessary information is exposed and the implementation details are concealed from the outside world, the code is made more secure.
  • It allows for the creation of objects with clearly defined properties and behaviors, which facilitates the reuse of the code throughout the program.
  • The implementation details are concealed and only the necessary methods are exposed, it aids in maintaining a clean codebase.

Python supports encapsulation through the use of classes and is an object-oriented programming language. Python class variables can be made private, public, or protected to achieve encapsulation.

Looking to Learn Python? Book a Free Trial Lesson and match with top Python Tutors for concepts, projects and assignment help on Wiingy today!

Encapsulation in Python

Encapsulation is achieved in Python through the use of classes. A class is a blueprint for creating objects, and it defines the properties and behaviors of an object. In Python, encapsulation is achieved through the use of access modifiers and getter and setter methods.

A. Defining classes in Python

In Python, classes are defined using the “class” keyword followed by the name of the class. The class definition can contain class variables and methods.

Public access

Public variables and methods are those that can be accessed by any part of the program. In Python, variables and methods are public by default, and they do not require any special keyword to be declared as public.

Example:

1class Car:
2    color = "red"
3    
4    def start(self):
5        print("Car started!")

In the above example, the “color” variable and the “start” method are public and can be accessed by any part of the program.

Private access

Private variables and methods are those that can only be accessed within the class. In Python, private variables and methods are declared by prefixing them with double underscores (__).

Example:

1class Car:
2    __engine_capacity = "2000cc"
3    
4    def __start_engine(self):
5        print("Engine started!")

In the above example, the “__engine_capacity” variable and the “__start_engine” method are private and can only be accessed within the “Car” class.

Protected access

Protected variables and methods are those that can be accessed within the class and its subclasses. In Python, protected variables and methods are declared by prefixing them with a single underscore (_).

Example:

1class Car:
2    _mileage = 0
3    
4    def _drive(self):
5        self._mileage += 10

In the above example, the “_mileage” variable and the “_drive” method are protected and can be accessed within the “Car” class and its subclasses.

B. Access Modifiers

Access to variables and methods in a class can be managed using access modifiers. Underscores are used in Python to create access modifiers.

Private access modifier

As mentioned earlier, private variables and methods in Python are declared by prefixing them with double underscores (__). Private variables cannot be accessed outside the class, and private methods can only be called from within the class.

Example:

1class Person:
2    __name = "John"
3    
4    def __greet(self):
5        print("Hello, my name is", self.__name)
6
7p = Person()
8p.__name # this will give an error as __name is a private variable
9p.__greet() # this will give an error as __greet is a private method
10Protected access modifier

Protected variables and methods in Python are declared by prefixing them with a single underscore (_). Protected variables can be accessed within the class and its subclasses, but they cannot be accessed outside the class hierarchy.

Example:

1class Animal:
2    _legs = 4
3    
4    def _walk(self):
5        print("Animal is walking")
6
7class Dog(Animal):
8    def bark(self):
9        print("Woof!")
10
11d = Dog()
12print(d._legs) # this will print 4 as _legs is a protected variable
13d._walk() # this will call the _walk method from the Animal class
14Public access modifier

Public variables and methods in Python do not require any access modifier, and they can be accessed by any part of the program.

Example:

1class Rectangle:
2    length = 5
3    breadth = 10
4    
5    def area(self):
6        return self.length * self.breadth
7
8r = Rectangle()
9print(r.area()) # this will print 50 as the area method is public

C. Getter and Setter Methods

Getter and setter methods are used to access and modify private variables in a class. Getter methods are used to get the value of a private variable, and setter methods are used to set the value of a private variable.

Example:

1class Person:
2    __name = "John"
3    
4    def get_name(self):
5        return self.__name
6    
7    def set_name(self, name):
8        self.__name = name
9
10p = Person()
11print(p.get_name()) # this will print John
12p.set_name("Mike")
13print(p.get_name()) # this will print Mike

D. Property Decorators

Python provides property decorators to simplify the process of using getter and setter methods. Property decorators are used to define getter and setter methods for a property.

Example:

1class Person:
2    def __init__(self, name):
3        self.__name = name
4    
5    @property
6    def name(self):
7        return self.__name
8    
9    @name.setter
10    def name(self, name):
11        self.__name = name
12
13p = Person("John")
14print(p.name) # this will print John
15p.name = "Mike"
16print(p.name) # this will print Mike

Advantages of Encapsulation in Python

A. Code Reusability

By enabling the creation of objects with clearly defined properties and behaviors, encapsulation promotes code reusability. This makes it simpler to reuse the code without having to change it in various areas of the program.

B. Security

By obscuring a class’s internal operations and exposing only what is necessary for external users to interact with the class, encapsulation enhances security. This stops unauthorized access to a class’s internal data.

C. Maintaining a Clean Codebase

By hiding a class’s implementation details and exposing only the necessary methods, encapsulation aids in maintaining a clean codebase.

Examples of Encapsulation in Python

Examples that highlight the use of private attributes, getter and setter methods, and property decorators can be used to illustrate encapsulation in Python.

A. Creating a class with private attributes

1/Code start/
2class BankAccount:
3    def __init__(self):
4        self.__balance = 0
5        
6    def deposit(self, amount):
7        self.__balance += amount
8        
9    def withdraw(self, amount):
10        if amount > self.__balance:
11            print("Insufficient balance")
12        else:
13            self.__balance -= amount
14            
15    def get_balance(self):
16        return self.__balance
17
18b = BankAccount()
19b.deposit(1000)
20b.withdraw(500)
21print(b.get_balance()) # this will print 500

In the above example, the “balance” attribute is declared as private, and it can only be accessed through the “get_balance” method. This ensures that the internal data of the “BankAccount” class is secure and can only be accessed in a controlled manner.

B. Using Getter and Setter methods

1class Employee:
2    def __init__(self):
3        self.__salary = 0
4        
5    def set_salary(self, salary):
6        self.__salary = salary
7        
8    def get_salary(self):
9        return self.__salary
10
11e = Employee()
12e.set_salary(50000)
13print(e.get_salary()) # this will print 50000

In the above example, the “salary” attribute is declared as private, and it can only be accessed through the “get_salary” method and modified through the “set_salary” method. This ensures that the internal data of the “Employee” class is secure and can only be accessed and modified in a controlled manner.

C. Implementing Property Decorators

1class Person:
2    def __init__(self, name):
3        self.__name = name
4    
5    @property
6    def name(self):
7        return self.__name
8    
9    @name.setter
10    def name(self, name):
11        self.__name = name
12
13p = Person("John")
14print(p.name) # this will print John
15p.name = "Mike"
16print(p.name) # this will print Mike

In the above example, the “name” attribute is declared as private, and it can only be accessed and modified through the “name” property decorator. This simplifies the process of using getter and setter methods and ensures that the internal data of the “Person” class is secure and can only be accessed and modified in a controlled manner.

Encapsulation vs. Abstraction

A. Explanation of Abstraction

Another fundamental idea in object-oriented programming is abstraction, which refers to the practice of hiding a class’s implementation specifics and exposing only its core functionality. Abstraction gives the class a high-level perspective that makes it simpler to use and comprehend.

B. Differences between Encapsulation and Abstraction

Encapsulation is the practice of keeping a class’ internal data hidden and only exposing what is required for external interactions. On the other hand, abstraction is the practice of hiding a class’s implementation specifics and exposing only its core features. Encapsulation deals with data concealment, whereas abstraction simplifies a class’s user interface.

C. How Encapsulation and Abstraction are used together

In object-oriented programming, encapsulation and abstraction are combined to produce well-structured, maintainable code. Encapsulation offers security by hiding a class’s internal data, and abstraction streamlines a class’s interface to make it simpler to use and comprehend. Encapsulation and abstraction work together to produce reusable, modular code.

Conclusion

A key idea in Python and object-oriented programming is encapsulation. By concealing a class’s internal data and only exposing that which is required for external interaction, it offers security. Additionally, encapsulation encourages code reuse, maintains a clean codebase, and offers flexibility by enabling implementation details to be changed without having an impact on other parts of the system.

It’s crucial to comprehend the benefits of encapsulation as a beginner to Python and object-oriented programming. Encapsulation enables you to write well-organized, maintainable code, which is crucial for developing intricate software systems. To implement encapsulation effectively, it’s also crucial to practice using private variables, getter and setter methods, and property decorators in your code. With practice, you will become more proficient in using encapsulation and other object-oriented programming concepts in Python.

Looking to Learn Python? Book a Free Trial Lesson and match with top Python Tutors for concepts, projects and assignment help on Wiingy today!

FAQs

What is encapsulation with example?

Encapsulation is the practice of keeping a class’ implementation details a secret and revealing only the information required for external interactions. Using the double underscore (__) prefix to declare a class variable private and using a getter method to access it are two examples of encapsulation in Python

Example:
class Person:
    __name = “John”
    def get_name(self):
        return self.__name
p = Person()
print(p.get_name()) # this will print John

What is encapsulation and Abstraction in Python?

Encapsulation and abstraction are two core principles of object-oriented programming in Python. Encapsulation is the practice of hiding the internal data of a class and exposing only what is necessary for the outside world to interact with the class. Abstraction is the practice of hiding the implementation details of a class and exposing only the essential features.

How many types of encapsulation are there in Python?

In Python, there are three types of encapsulation:
Private access: declared using double underscores (__)
Protected access: declared using a single underscore (_)
Public access: default access modifier

What is encapsulation in Python educative?

They cover the idea of encapsulation in Python educational in their course on python object-oriented programming. Encapsulation is covered in the course along with other fundamental concepts of OOP like inheritance, polymorphism, and abstraction.

Find Expert Subject Tutor

Find top-rated tutors

Popular

subject

Singing

subject

Math

subject

English

subject

Spanish

subject

Guitar

subject

Piano

subject

Algebra

subject

Calculus

subject

Physics

subject

Chemistry

subject

Biology

subject

AP Calculus

subject

SAT Test

subject

ACT Test

subject

Economics

subject

ESL

subject

Coding

subject

French

subject

Python

subject

Electrical Engineering

subject

Java

subject

Electronics Engineering

subject

Revit

subject

Organic Chemistry

Victoria Frisher - Singing tutor

Dynamic Singing Tutor with over 9 years of experience and a Master’s in Music specializing in pop vocals. I’ve worked with 200+ students, offering personalized, hands-on lessons that bring out your best. Let’s develop your voice and boost your confidence together!

Hello, I'm Victoria Frisher, I'm a professional singing tutor and singer. With a Masters degree in Music and professional qualifications as a pop lead vocalist, ensemble vocalist, voice teacher in higher education, and music arts manager. I've been working as a vocal participant of many cover projects, backing vocalist and vocal teacher. I have over 15 years of performing practice, extensive studio work and more than 9 years of teaching experience. I bring a wealth of experience to my teaching. My teaching philosophy revolves around creating a supportive and nurturing environment where students feel motivated to explore their musical abilities. I believe in tailoring my approach to suit each student's learning style and pace, ensuring personalized attention and growth. I engage students by incorporating a mix of modern and traditional vocal techniques, modern music trends, and interactive learning activities. By making lessons fun and interactive, I aim to inspire a love for music and build confidence in my students at all levels. I am excited to share my passion for music with you and help you reach your full potential as a singer. Let's embark on this musical journey together!

Free trial lesson

4.8

(85)

$30

/ hour

Super Tutor

Karine Longis McMillan - English tutor

Experienced English Tutor with 15+ Years of Experience and a Doctorate in Psychology in Education. Interactive, Creative, and Practical Lessons to Enhance Problem-Solving Skills. Join 200+ Students in Engaging Hands-On Learning at University of Toulouse Graduate!

Hello! I'm Karine Longis McMillan, a Doctorate degree holder specializing in Psychology in Education from France. I also have a Teaching degree from Ireland and a Masters in Eduction from England. With a passion for teaching English, I offer tutoring in ESL, IELTS, and English for students of all levels. I currently reside in France with my family. I have been teaching for over 16 years and I love what I do. I have worked on different continents and with people of different age and from different professional background. My teaching philosophy centers around creating a supportive and engaging learning environment where students feel motivated to excel. I believe in personalized learning to cater to individual needs and learning styles. Through interactive and practical lessons, I aim to enhance not only language skills but also critical thinking and communication abilities. Let's embark on a journey of language learning together! We can talk about daily activities, travelling or focus more a professional approach. You tell me what you need and I work to help you achieve your goals without any kind of stress on your parts. I am also very flexible in the hours I work. So do not hesitate to contact me!

Free trial lesson

4.8

(113)

$40

$32

/ hour

Super Tutor

Show all
placeholder
Reviewed by Wiingy

Jan 30, 2025

Was this helpful?

You might also like


Explore more topics