Access Modifiers

Some parts, like the engine, you want to be accessible for repairs. But others, like the computer system, are very delicate, and you only want trained mechanics to mess with them. That’s where access modifiers come in.

They control which parts of the code can be accessed and modified from different places.

Python has three types of access modifiers:

Public: Think of these as the accessible parts of the car. Any mechanic can access and modify public attributes and methods. They’re declared by simply writing their names directly in the class.

 1class Car:
 2   def __init__(self):
 3       # Public attribute
 4       self.make = "Toyota"
 5       # Public attribute
 6       self.model = "Tacoma"
 7       # Public attribute
 8       self.color = "white"
 9
10   # Public method
11   def start_engine(self):  
12       print("Engine started") 
13
14my_car = Car()
15my_car.start_engine()
16# Engine started

Protected (_ prefix): These are like those engine parts you want to be cautious with.
They’re marked with an underscore (_) prefix. While technically accessible from outside the class, they signal that they’re meant to be used mainly within the class and its subclasses like specialized mechanics working on specific car types or parts.

 1class Car:
 2   def __init__(self):
 3       # Protected attribute
 4       self._mileage = 0 
 5
 6   # Protected method `_` 
 7   def _update_mileage(self, miles):  
 8       self._mileage += miles 
 9
10class SportsCar(Car):
11   def __init__(self):
12       super().__init__()
13       # SportsCar can access and modify _mileage
14       self._boost_level = 1   

Private (__ prefix): These are the computer system - off-limits to everyone except the internal mechanisms of the car itself. They’re marked with a double underscore (__) prefix. Python does some name mangling to make them truly private, preventing access from outside the class.

 1class Car: 
 2 def __init__(self):
 3     # Private attribute `__`
 4     self.__vin = "123XYZ789ABC"  
 5     
 6 # Private function `__`
 7 def __update_software(self):  
 8     print("Updating internal car software.") 
 9
10my_car = Car()
11# print(f"{my_car.__vin}")  # raises an AttributeError
12# my_car.__update_software()  # raises an AttributeError

Why Are Access Modifiers Important?

  • Data Protection: They help prevent accidental modification of critical attributes and maintain data integrity.
  • Controlled Access: They enforce rules about how different parts of your code should interact with each other, promoting better organization and maintainability.
  • Flexibility for Future Changes: You can change the internal implementation of a class without breaking external code, as long as the public interface remains consistent.

Car example:

  • Public: The start_engine() function is public because anyone driving the car should be able to start it.
  • Protected: The _mileage attribute is protected because while it’s important information, it should only be modified through specific methods within the Car class and its subclasses (like _update_mileage()).
  • Private: The __vin attribute and __update_software() function are private because they deal with highly sensitive internal data and processes that shouldn’t be tampered with externally.

Notes:

Python’s access modifiers are more like guidelines than strict rules. However, using them properly significantly improves the security, maintainability, and overall quality of the code.

Read: Python DataClasses Decorator