Encapsulation

Encapsulation is the packing of data and functions into a single component.

Python Example

For more Python class related examples, see:

In Python, private variables are named beginning with double underscore characters.

# Define a class containing a private variable: __value.
class Counter:
  
    # Declare the private variable.
    __value = None
  
    # Class constructor.
    def __init__(self, initial_value):
    
        # Initialize a private variable.
        self.__value = initial_value
  
    # Get the counter.
    def get_value(self):
        return self.__value
  
    # Set the counter.
    def set_value(self, value):
        self.__value = value
    
    # Decrease the counter.
    def decrease_value(self):
        self.__value -= 1
        if self.__value < 0:
            self.__value = 0
  
# Instantiate the Counter class. 
counter = Counter(4)
 
# Use the counter methods. 
print(counter.get_value())
counter.set_value(3)
counter.decrease_value()
print(counter.get_value())