Python Encapsulation | Learn Coding
Python Interview Questions: encapsulation in python, python encapsulation , what is OOP in python
python encapsulation, Python Object Oriented Programming, encapsulation, encapsulation in python, encapsulation in oops, encapsulation python
Python Notes:
What is Encapsulation in Python?
Encapsulation in Python describes the concept of bundling data and methods within a single unit. So, for example, when you create a class, it means you are implementing encapsulation. A class is an example of encapsulation as it binds all the data members (instance variables) and methods into a single unit.
In Python, we do not have access modifiers, such as public, private, and protected. But we can achieve encapsulation by using prefix single underscore and double underscore to control access of variable and method within the Python program.
class Employee:
def __init__(self, name):
self.name = name
self._age = 30
self.__salary = 2000
# getter method
def get_age(self):
return self._age
# setter method
def set_age(self, age):
if age == 0:
print('Invalid Age')
else:
self._age = age
def register(self):
print(f'{ self.name } is registered')
def getSalaryDetails(self):
print(f'{ self.name } Salary is: { self.__salary } ')
e = Employee('Raj')
e.register()
e.getSalaryDetails()
# Mangling
print('Mangling to access private members for salary:', e._Employee__salary)
e.set_age(0)
print(e.get_age())
In the above example, we create a class called Employee. Within that class, we declare two variables name and __salary. We can observe that the name variable is accessible, but __salary is the private variable. We cannot access it from outside of class. If we try to access it, we will get an error
Name Mangling to access private members
We can directly access private and protected variables from outside of a class through name mangling. The name mangling is created on an identifier by adding two leading underscores and one trailing underscore, like this _classname__dataMember, where classname is the current class, and data member is the private variable name.
# Mangling
print('Mangling to access private members for salary:', e._Employee__salary)
Getters and Setters in Python
To implement proper encapsulation in Python, we need to use setters and getters. The primary purpose of using getters and setters in object-oriented programs is to ensure data encapsulation. Use the getter method to access data members and the setter methods to modify the data members.
In Python, private variables are not hidden fields like in other programming languages. The getters and setters methods are often used when:
1. When we want to avoid direct access to private variables
2. To add validation logic for setting a value
#encapsulation #oop #python #pythonforbeginners
Channel: https://www.youtube.com/@NewsOnCoding
? - FACEBOOK: https://www.facebook.com/profile.php?id=100094506555328
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Python Encapsulation | Learn Coding», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.