Menu
Coddy logo textTech

Access Modifiers

Part of the Object Oriented Programming section of Coddy's Python journey — lesson 29 of 64.

Access modifiers control the visibility of class attributes and methods. Python uses naming conventions rather than keywords for access control.

Here is an example of public access (no prefix):

class Person:
    def __init__(self):
        self.name = "Coddy"      # Public attribute
        
    def greet(self):             # Public method
        return f"Hello, I'm {self.name}"

Access public members from anywhere:

person = Person()
print(person.name)           # Coddy
print(person.greet())        # Hello, I'm Coddy

Here is an example of protected access (single underscore):

class Employee:
    def __init__(self):
        self._salary = 50000     # Protected attribute
    
    def _calculate_bonus(self):  # Protected method
        return self._salary * 0.1

    def show_bonus(self):
        return self._calculate_bonus()  # OK to use within class

Access protected members (works but not recommended):

employee = Employee()
print(employee._salary)      # 50000 - works but discouraged
print(employee.show_bonus()) # 5000.0 - proper way

Here is an example of private access (double underscore):

class User:
    def __init__(self):
        self.__password = "secure123"   # Private attribute
        
    def __encrypt(self, data):          # Private method
        return f"Encrypted: {data}"
        
    def verify(self, input_password):
        # Private members accessible inside the class
        return input_password == self.__password

Use private members correctly:

user = User()
print(user.verify("secure123"))  # True - using public method
# print(user.__password)         # AttributeError - cannot access directly

Output:

Coddy
Hello, I'm Coddy
50000
5000.0
True

Key Point: Python access modifiers are naming conventions: no prefix = public (accessible anywhere), single underscore = protected (internal use), double underscore = private (class only). These help establish clear boundaries and prevent accidental misuse of class internals.

challenge icon

Challenge

Medium

In this challenge, you'll implement a FileManager class that demonstrates Python's access modifiers (public, protected, and private) while experiencing the benefits of comprehensive testing.

Edit filemanager.py to implement the FileManager class following the TODO comments. The file contains detailed instructions for implementing:

  • Public methods for file operations
  • Protected methods (with single underscore prefix)
  • Private methods (with double underscore prefix)
  • Method interactions demonstrating encapsulation

Cheat sheet

Python uses naming conventions for access control:

Public access (no prefix) - accessible anywhere:

class Person:
    def __init__(self):
        self.name = "Coddy"      # Public attribute
        
    def greet(self):             # Public method
        return f"Hello, I'm {self.name}"

person = Person()
print(person.name)           # Coddy
print(person.greet())        # Hello, I'm Coddy

Protected access (single underscore) - internal use, discouraged from outside:

class Employee:
    def __init__(self):
        self._salary = 50000     # Protected attribute
    
    def _calculate_bonus(self):  # Protected method
        return self._salary * 0.1

employee = Employee()
print(employee._salary)      # Works but discouraged

Private access (double underscore) - class only:

class User:
    def __init__(self):
        self.__password = "secure123"   # Private attribute
        
    def __encrypt(self, data):          # Private method
        return f"Encrypted: {data}"
        
    def verify(self, input_password):
        return input_password == self.__password

user = User()
print(user.verify("secure123"))  # True - using public method
# print(user.__password)         # AttributeError - cannot access directly

Try it yourself

from file_manager import FileManager

# Comprehensive test case handler
test_case = input()

if test_case == "basic_test":
    # Create a FileManager instance
    manager = FileManager()
    # Call the read_file method
    print(manager.read_file("example.txt"))
    # Call the get_file_content method
    print(manager.get_file_content("example.txt"))

elif test_case == "protected_access":
    # Create a FileManager instance
    manager = FileManager()
    # Try to call the protected method
    # Protected methods are accessible but intended for internal use
    print(manager._check_permissions("example.txt"))
    print("Note: Protected methods are accessible but intended for internal use only")

elif test_case == "private_access":
    # Create a FileManager instance
    manager = FileManager()
    try:
        # Try to call the private method directly
        print(manager.__decrypt_content("some content"))
    except AttributeError as e:
        print(f"Error: {e}")
        print("Private methods are name-mangled and cannot be accessed directly")
    
    # Access using name-mangled form
    print(manager._FileManager__decrypt_content("some content"))
    print("Note: Accessed private method using name-mangled form")

elif test_case == "method_chaining":
    # Create a FileManager instance
    manager = FileManager()
    # Demonstrate how get_file_content internally calls both protected and private methods
    print("Calling get_file_content which internally uses protected and private methods:")
    print(manager.get_file_content("example.txt"))

elif test_case == "multiple_files":
    # Create a FileManager instance
    manager = FileManager()
    # Process multiple files
    files = ["document.txt", "image.jpg", "data.csv"]
    
    for file in files:
        print(f"\
Processing {file}:")
        print(manager.read_file(file))
        print(manager.get_file_content(file))

elif test_case == "name_mangling":
    # Create a FileManager instance
    manager = FileManager()
    # Demonstrate name mangling
    print("Python's name mangling for private methods:")
    print("Attempting direct access would fail with AttributeError")
    print("Using mangled name:")
    print(manager._FileManager__decrypt_content("private data"))
    print("\
Name mangling is Python's mechanism to prevent accidental access")
    print("It renames __method to _ClassName__method internally")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming