10.3 Encapsulation

Three Types of Access modifiers.

  1. >Public: Can be accessed anywhere in the program. All variables are public by default.
  2. >Protected: Only the current class and derived class can access them. Use "_<variable_name>" to define them.
  3. >Private: Only the current class can access them, not even their instance can access them. Use "__<variable_name>" to define them.

10.3.1 property(fget=None, fset=None, fdel=None, doc=None) => property

Parameters:

  • >fget Optional[Callable]: The getter function.
  • >fset Optional[Callable]: The setter function.
  • >fdel Optional[Callable]: The deleter function.
  • >doc Optional[str]: Provide some information about this property.

Explanation: It is a Pythonic way to use getters and setters in encapsulation. property() function simply allows assigning/altering private variables using the '.' operator without really exposing the real (private) variable. Using this function accessing/modifying becomes just as convenient as operating on a regular variable. property() can also be used as a decorator for further convenience. For more implementation details check Official Python docs.
Descriptor vs Property: Descriptors are the low-level mechanism behind allowing class variables to control what happens during attribute lookup. And properties are descriptors, they are an implementation of descriptors. Although one drawback using descriptors is that for every variable it requires a separate class, which is not the case with properties. One can have multiple variables of such behaviour inside a single class using properties.