Encapsulation

Encapsulation - process of wrapping data and functions which operate on that data into a single unit, the class. Or restricting direct access to some object’s components.

Many programming languages use encapsulation frequently in the form of classes. A class is an example of encapsulation in computer science.

Data Hiding - It is the technique of hiding the implementation details of an object. It is the result of Encapsulation.

Encapsulation
Encapsulation

Getters and setters are used to ensure data encapsulation in OOP.

In Python they are not the same as in other languages, because private variables are not hidden in python. But they add validation for getting and setting values or to avoid direct access of a class field.

class P:
  def __init__(self, x):
      self.x = x

  @property
  def x(self):
      return self._x

  @x.setter
  def x(self, x):
      if x < 0:
          self._x = 0
      elif x > 1000:
          self._x = 1000
      else:
          self._x = x
class Person:
	def __init__(self, first_name):
		self.first_name = first_name
	
	@property
	def first_name(self):
		return self._first_name

	@first_name.setter
	def first_name(self, value):
		if not instance(value, str):
			raise TypeError('Excected String')
		self._first_name = value

	@first_name.deleter
	def first_mame(self):
		raise AttributeError("Can't delete an attribute")
			

Encapsulation vs Abstraction

Abstraction vs encapsulation
Abstraction vs encapsulation

References

SuperMade with Super