- Access modifiers ā controlling visibility of class members
- Public ā default, accessible from anywhere
- Protected ā intended for internal use and subclasses
- Private ā hidden from outside, with name mangling
- Name mangling ā how Python makes private members truly private
- Encapsulation ā protecting data and implementation details
What are Access Modifiers?
Access modifiers control the visibility of class attributes and methods. They help implement encapsulation ā one of the core principles of Object-Oriented Programming.
Unlike languages like Java or C++ that have explicit keywords (public, private, protected), Python takes a convention-based approach:
- Public ā
name(no underscore) - Protected ā
_name(single underscore) - Private ā
__name(double underscore)
Python's philosophy is: "We're all consenting adults here." The language trusts developers to respect the conventions rather than enforcing them rigidly.
š” Key concept: Python's access modifiers are conventions ā they signal intent to other developers, but don't prevent access. The exception is double-underscore (__name) which triggers name mangling.
Public Members
The Default Visibility
In Python, everything is public by default. Public members can be accessed from anywhere ā inside the class, outside the class, and in subclasses.
Public members are defined without any leading underscores. They're the "normal" way to define attributes and methods.
# Public Members ā Default Visibility
class Person:
def __init__(self, name, age):
self.name = name # Public attribute
self.age = age # Public attribute
# Public method
def introduce(self):
return f"Hi, I'm {self.name} and I'm {self.age} years old"
# Public method
def celebrate_birthday(self):
self.age += 1
return f"Happy Birthday! Now {self.age} years old"
# Access from outside
person = Person("Alice", 25)
print(person.name) # Alice ā accessible
print(person.age) # 25 ā accessible
print(person.introduce()) # Hi, I'm Alice and I'm 25 years old
print(person.celebrate_birthday()) # Happy Birthday! Now 26 years old
# Subclass can also access public members
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def show_info(self):
# Accessing parent's public members
return f"{self.name} is in grade {self.grade}"
student = Student("Bob", 18, 12)
print(student.show_info()) # Bob is in grade 12
print(student.name) # Bob ā accessible
print("\nā
Public members: accessible from anywhere")
print("ā
No special syntax needed ā just use the name")
Public key points:
- Default visibility ā no underscores needed
- Accessible everywhere ā inside class, outside, in subclasses
- Convention ā used for the public API of your class
- No restrictions ā Python doesn't prevent access
Quick Check: How do you define a public attribute in Python? (Answer: Just use the name without any underscores, e.g., self.name)
Protected Members
Single Underscore Convention
Protected members are indicated by a single leading underscore (_name). They signal: "This is intended for internal use. Don't access it from outside."
Protected members can still be accessed from outside, but the underscore is a convention telling developers: "You shouldn't touch this unless you know what you're doing."
# Protected Members ā Single Underscore Convention
class BankAccount:
def __init__(self, account_holder, balance):
self.account_holder = account_holder # Public
self._balance = balance # Protected ā internal use
self._transaction_history = [] # Protected ā internal use
# Public method ā API for users
def deposit(self, amount):
if amount > 0:
self._balance += amount
self._add_transaction(f"Deposit: +${amount}")
return f"Deposited ${amount}. New balance: ${self._balance}"
return "Invalid amount"
# Public method ā API for users
def withdraw(self, amount):
if 0 < amount <= self._balance:
self._balance -= amount
self._add_transaction(f"Withdrawal: -${amount}")
return f"Withdrew ${amount}. New balance: ${self._balance}"
return "Insufficient funds or invalid amount"
# Public method ā API for users
def get_balance(self):
return self._balance
# Protected method ā internal helper
def _add_transaction(self, description):
self._transaction_history.append(description)
# Protected method ā internal helper
def _get_transaction_history(self):
return self._transaction_history
class SavingsAccount(BankAccount):
def __init__(self, account_holder, balance, interest_rate):
super().__init__(account_holder, balance)
self._interest_rate = interest_rate
# Can access protected members from parent
def apply_interest(self):
interest = self._balance * self._interest_rate / 100
self._balance += interest
self._add_transaction(f"Interest: +${interest:.2f}")
return f"Interest applied: ${interest:.2f}"
def get_transactions(self):
# Accessing protected method from parent
return self._get_transaction_history()
# --- Using the class ---
account = BankAccount("Alice", 1000)
print(account.deposit(500)) # Deposited $500. New balance: $1500
print(account.withdraw(200)) # Withdrew $200. New balance: $1300
# Protected members can be accessed, but it's discouraged
print(account._balance) # 1300 ā accessible but discouraged
print(account._transaction_history) # accessible but discouraged
# Subclass can access protected members
savings = SavingsAccount("Bob", 1000, 2.5)
print(savings.apply_interest()) # Interest applied: $25.00
print(savings.get_transactions())
print("\nā
Protected members: single underscore ā convention, not enforcement")
print("ā ļø They can be accessed from outside, but don't do it!")
print("ā
Subclasses can access them freely")
Protected key points:
- Single underscore ā
_nameindicates protected - Convention only ā no enforcement by Python
- For internal use ā intended for class and subclasses
- Accessible from subclasses ā designed for inheritance
- Discouraged from outside ā signals "don't touch"
Quick Check: What does a single underscore prefix (_name) indicate? (Answer: Protected ā intended for internal use and subclasses, but just a convention)
Private Members
Double Underscore and Name Mangling
Private members are indicated by a double leading underscore (__name). Unlike protected, private members cannot be accessed from outside the class ā at least not easily.
Python uses name mangling to make private members harder to access. The name is changed to _ClassName__name, which prevents accidental access.
# Private Members ā Double Underscore and Name Mangling
class BankAccount:
def __init__(self, account_holder, balance):
self.account_holder = account_holder # Public
self.__balance = balance # Private ā name mangling
self.__transaction_history = [] # Private ā name mangling
self.__account_number = self.__generate_account_number()
# Private method ā name mangled
def __generate_account_number(self):
import random
return f"ACC-{random.randint(10000, 99999)}"
# Public method ā API for users
def deposit(self, amount):
if amount > 0:
self.__balance += amount
self.__add_transaction(f"Deposit: +${amount}")
return f"Deposited ${amount}. New balance: ${self.__balance}"
return "Invalid amount"
# Public method ā API for users
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
self.__add_transaction(f"Withdrawal: -${amount}")
return f"Withdrew ${amount}. New balance: ${self.__balance}"
return "Insufficient funds or invalid amount"
# Public method ā API for users
def get_balance(self):
return self.__balance
def get_account_info(self):
return f"{self.account_holder} - {self.__account_number}"
# Private method ā name mangled
def __add_transaction(self, description):
self.__transaction_history.append(description)
# Protected method ā exposes private data safely
def _get_transactions(self):
# Return a copy to prevent modification
return self.__transaction_history.copy()
class SavingsAccount(BankAccount):
def __init__(self, account_holder, balance, interest_rate):
super().__init__(account_holder, balance)
self._interest_rate = interest_rate
def apply_interest(self):
# Cannot access __balance directly ā name mangled!
# self.__balance += interest # This would create a NEW attribute!
# Must use the public method
balance = self.get_balance()
interest = balance * self._interest_rate / 100
self.deposit(interest)
return f"Interest applied: ${interest:.2f}"
# --- Using the class ---
account = BankAccount("Alice", 1000)
print(account.deposit(500)) # Deposited $500. New balance: $1500
print(account.withdraw(200)) # Withdrew $200. New balance: $1300
print(account.get_account_info())
# Private members are NOT accessible
# print(account.__balance) # AttributeError!
# print(account.__transaction_history) # AttributeError!
# print(account.__generate_account_number()) # AttributeError!
# But they can be accessed via name mangling (but don't do this!)
print(account._BankAccount__balance) # 1300 ā name mangled access
print(account._BankAccount__transaction_history)
# Subclass cannot access private members
savings = SavingsAccount("Bob", 1000, 2.5)
print(savings.apply_interest()) # Interest applied: $25.00
# print(savings.__balance) # AttributeError!
# print(savings.__transaction_history) # AttributeError!
print("\nā
Private members: double underscore ā name mangling")
print("ā Cannot access directly from outside")
print("ā ļø Subclasses also cannot access private members of parent")
print("š§ Name mangling: _ClassName__name (but this is a hack)")
Private key points:
- Double underscore ā
__nameindicates private - Name mangling ā changed to
_ClassName__name - Not accessible outside ā direct access raises AttributeError
- Not accessible in subclasses ā name mangling prevents
- Can be accessed via mangled name ā but this is a hack
Quick Check: How does Python make private members inaccessible from outside? (Answer: Name mangling ā __name becomes _ClassName__name)
Name Mangling Explained
How Private Members Are Protected
Name mangling is Python's way of making private members "private." When you define an attribute with two leading underscores (__name), Python automatically changes the name to _ClassName__name.
This prevents accidental access from outside the class and prevents subclasses from accidentally overriding private methods.
# Name Mangling ā How Private Members Work
class Parent:
def __init__(self):
self.__private = "I'm private"
self._protected = "I'm protected"
self.public = "I'm public"
def __private_method(self):
return "Private method called"
def _protected_method(self):
return "Protected method called"
def public_method(self):
return "Public method called"
def show_private(self):
# Can access private from inside the class
return f"Inside: {self.__private}"
class Child(Parent):
def __init__(self):
super().__init__()
# This creates a DIFFERENT attribute ā not overriding parent's
self.__private = "Child's private"
def try_access_parent_private(self):
# Cannot access parent's __private directly
# return self.__private # Returns child's __private, not parent's
# Need to use the public method
return self.show_private()
def get_mangled_name(self):
# The mangled name for parent's private
return "Parent's __private becomes: _Parent__private"
# --- Demonstration ---
parent = Parent()
child = Child()
# Public ā accessible
print(parent.public) # I'm public
print(parent.public_method()) # Public method called
# Protected ā accessible but discouraged
print(parent._protected) # I'm protected
print(parent._protected_method()) # Protected method called
# Private ā not directly accessible
# print(parent.__private) # AttributeError!
# print(parent.__private_method()) # AttributeError!
# But we can see the mangled name
print(dir(parent))
# ... includes _Parent__private, _Parent__private_method
# Accessing via mangled name (hack ā don't do this!)
print(parent._Parent__private) # I'm private
print(parent._Parent__private_method()) # Private method called
# Child class
print(child._protected) # I'm protected (inherited)
print(child.show_private()) # Inside: I'm private
print(child.try_access_parent_private()) # Inside: I'm private
# Child's own __private is different
print(child._Child__private) # Child's private
print("\n" + "=" * 60)
print("NAME MANGLING SUMMARY")
print("=" * 60)
print("""
| Original Name | Mangled Name | Purpose |
|---------------|----------------------------|----------------------------|
| __private | _ClassName__private | Prevent accidental access |
| __method() | _ClassName__method() | Prevent subclass override |
WHY NAME MANGLING?
1. Prevents accidental attribute access from outside
2. Prevents subclasses from accidentally overriding
3. Makes private truly private (to the class)
4. Follows the "consenting adults" principle
ā ļø Important: Name mangling is NOT security!
It's a protection against accidents, not malicious access.
Anyone can still access using the mangled name.
""")
Name mangling key points:
- Transforms ā
__nameā_ClassName__name - Prevents accidental access ā from outside and subclasses
- Allows overriding safely ā subclasses can have their own
__name - Not security ā it's a convention, not a wall
- Can be bypassed ā using the mangled name directly
Quick Check: What is name mangling and why is it used? (Answer: Python changes __name to _ClassName__name to prevent accidental access and subclass overriding)
Comparison Table
Public vs Protected vs Private ā Side by Side
# Access Modifiers ā Complete Comparison
class AccessDemo:
def __init__(self):
self.public = "Public" # No underscore
self._protected = "Protected" # Single underscore
self.__private = "Private" # Double underscore
def public_method(self):
return "Public method"
def _protected_method(self):
return "Protected method"
def __private_method(self):
return "Private method"
def access_all(self):
# Inside the class ā all accessible
return [
self.public,
self._protected,
self.__private,
self.public_method(),
self._protected_method(),
self.__private_method()
]
class Subclass(AccessDemo):
def __init__(self):
super().__init__()
self.public = "Subclass public"
self._protected = "Subclass protected"
# self.__private = "Subclass private" # This is different!
def access_parent(self):
# Can access public and protected from parent
parent_public = super().public
parent_protected = super()._protected
# Cannot access parent's private directly
# parent_private = super().__private # AttributeError
return parent_public, parent_protected
# ============================================================
# COMPARISON TABLE
# ============================================================
print("""
āāāāāāāāāāāāāāāāāāāāāāāāā¦āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā Access Modifier ā Visibility ā
ā āāāāāāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā£
ā ā ⢠No underscore ā
ā PUBLIC ā ⢠Accessible from anywhere ā
ā (name) ā ⢠Available in subclasses ā
ā ā ⢠The default for all members ā
ā āāāāāāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā£
ā ā ⢠Single underscore ā
ā PROTECTED ā ⢠Accessible inside class and subclasses ā
ā (_name) ā ⢠Can be accessed from outside (discouraged) ā
ā ā ⢠Signals "internal use ā don't touch" ā
ā āāāāāāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā£
ā ā ⢠Double underscore ā
ā PRIVATE ā ⢠Name mangled: _ClassName__name ā
ā (__name) ā ⢠Not accessible from outside (directly) ā
ā ā ⢠Not accessible in subclasses ā
ā ā ⢠Can be accessed via mangled name (hack) ā
āāāāāāāāāāāāāāāāāāāāāāāāā©āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
USAGE RECOMMENDATIONS:
⢠PUBLIC: Public API ā safe for external use
⢠PROTECTED: Internal implementation ā for subclasses
⢠PRIVATE: Implementation detail ā not for external use
""")
Comparison summary:
- Public ā no underscore, accessible everywhere
- Protected ā
_name, for internal use and subclasses - Private ā
__name, name mangled, class-only - Outside access ā public: yes, protected: yes (but discouraged), private: no (except hack)
- Subclass access ā public: yes, protected: yes, private: no
Quick Check: Which access modifier can subclasses access? (Answer: Public and protected ā private is not accessible in subclasses)
Real-World Example
Building a Secure User System
# Real-World Example: User Management System
import hashlib
import secrets
from datetime import datetime, timedelta
class User:
"""Secure user management with access modifiers"""
def __init__(self, username, email, password):
self.username = username # Public ā user identifier
self.email = email # Public ā contact info
self.__password_hash = None # Private ā password hash
self.__failed_login_attempts = 0 # Private ā security tracking
self.__last_login = None # Private ā login tracking
self.__session_token = None # Private ā authentication
self.__is_locked = False # Private ā account lock
self._role = "user" # Protected ā for subclasses
# Use protected method to set password
self._set_password(password)
self._log_event("Account created")
# ---- PUBLIC API ----
def login(self, password):
"""Public ā authenticate user"""
if self.__is_locked:
return "Account is locked. Contact support."
if self._verify_password(password):
self.__failed_login_attempts = 0
self.__last_login = datetime.now()
self.__session_token = self._generate_token()
self._log_event("Login successful")
return f"Welcome back, {self.username}!"
else:
self.__failed_login_attempts += 1
if self.__failed_login_attempts >= 3:
self.__is_locked = True
self._log_event("Account locked due to failed attempts")
return "Account locked due to too many failed attempts."
return "Invalid password."
def change_password(self, old_password, new_password):
"""Public ā change password with verification"""
if not self._verify_password(old_password):
self._log_event("Failed password change attempt")
return "Invalid current password."
if len(new_password) < 8:
return "Password must be at least 8 characters."
self._set_password(new_password)
self.__session_token = None # Invalidate old sessions
self._log_event("Password changed")
return "Password changed successfully."
def logout(self):
"""Public ā end session"""
self.__session_token = None
self._log_event("Logged out")
return "Logged out successfully."
def get_profile(self):
"""Public ā get user info (safe)"""
return {
"username": self.username,
"email": self.email,
"role": self._role,
"last_login": self.__last_login,
"is_locked": self.__is_locked
}
def reset_account(self):
"""Public ā reset security (admin only)"""
self.__failed_login_attempts = 0
self.__is_locked = False
self.__session_token = None
self._log_event("Account reset by admin")
return "Account reset successfully."
# ---- PROTECTED METHODS ----
def _set_password(self, password):
"""Protected ā hash and store password"""
salt = secrets.token_hex(16)
self.__password_hash = self._hash_password(password, salt)
def _verify_password(self, password):
"""Protected ā verify password against hash"""
if self.__password_hash is None:
return False
# In real code, extract salt and verify
# Simplified for demo
return True
def _hash_password(self, password, salt):
"""Protected ā hash password with salt"""
return hashlib.sha256((password + salt).encode()).hexdigest()
def _generate_token(self):
"""Protected ā generate session token"""
return secrets.token_urlsafe(32)
def _log_event(self, event):
"""Protected ā log user activity"""
print(f"[{datetime.now()}] {self.username}: {event}")
# ---- PRIVATE METHODS (Implementation Details) ----
def __validate_email(self):
"""Private ā email validation (name mangled)"""
# Implementation detail
return "@" in self.email and "." in self.email
class AdminUser(User):
"""Admin user with additional privileges"""
def __init__(self, username, email, password, admin_level):
super().__init__(username, email, password)
self._role = "admin" # Protected ā can modify
self.__admin_level = admin_level # Private
def promote_user(self, user):
"""Admin action ā promote a user"""
if isinstance(user, User):
user._role = "admin" # Access protected member
self._log_event(f"Promoted {user.username}")
return f"{user.username} promoted to admin."
return "Invalid user."
def demote_user(self, user):
"""Admin action ā demote a user"""
if isinstance(user, User):
user._role = "user"
self._log_event(f"Demoted {user.username}")
return f"{user.username} demoted to user."
return "Invalid user."
# ---- DEMO ----
print("=" * 60)
print("USER MANAGEMENT SYSTEM")
print("=" * 60)
# Create users
print("\n1. CREATING USERS")
user1 = User("alice", "alice@example.com", "SecurePass123")
user2 = User("bob", "bob@example.com", "MyPassword456")
admin = AdminUser("admin", "admin@example.com", "AdminPass789", 5)
# Login attempts
print("\n2. LOGIN ATTEMPTS")
print(user1.login("wrong")) # Invalid password.
print(user1.login("wrong")) # Invalid password.
print(user1.login("wrong")) # Account locked...
print(user1.login("SecurePass123")) # Account is locked. Contact support.
# Admin resets account
print("\n3. ADMIN ACTIONS")
print(admin.promote_user(user2)) # bob promoted to admin.
print(admin.reset_account(user1)) # Account reset successfully.
# User logs in again
print("\n4. LOGIN SUCCESS")
print(user1.login("SecurePass123")) # Welcome back, alice!
# Change password
print("\n5. CHANGE PASSWORD")
print(user1.change_password("SecurePass123", "NewStrongPass456"))
# Get profile
print("\n6. USER PROFILE")
print(user1.get_profile())
print("\nā
Public: username, email, profile methods")
print("ā
Protected: _role, _set_password(), _log_event()")
print("ā
Private: __password_hash, __failed_login_attempts, __session_token")
print("ā
Encapsulation: sensitive data is protected")
Real-world example key points:
- Public ā username, email, login(), logout(), get_profile()
- Protected ā _role, _set_password(), _verify_password(), _log_event()
- Private ā __password_hash, __failed_login_attempts, __session_token, __is_locked
- Encapsulation ā sensitive data hidden behind public API
- Security ā password hashing, account locking, failed attempt tracking
Quick Check: Why are password hash and session token private? (Answer: To protect sensitive security data from accidental modification or access)
Best Practices
Using Access Modifiers Effectively
# Best Practices for Access Modifiers
# ============================================================
# 1. PUBLIC ā The Safe API
# ============================================================
class SafeAPI:
def __init__(self):
self.name = "Public" # Public ā safe to access
self._internal = "Internal" # Protected ā not part of API
self.__secret = "Secret" # Private ā implementation detail
def public_method(self):
"""This is the public API ā documented and stable"""
return "Use this method"
def _internal_method(self):
"""Internal method ā may change"""
return "Don't depend on this"
def __secret_method(self):
"""Implementation detail ā don't touch"""
return "This might change or disappear"
# ā
DO: Keep public API clean and well-documented
# ā
DO: Use public methods for all external interactions
# ā DON'T: Make internal details public
# ============================================================
# 2. PROTECTED ā For Inheritance
# ============================================================
class BaseClass:
def __init__(self):
self._value = 0 # Protected ā for subclasses
def _helper_method(self):
"""Protected ā subclasses can use this"""
return self._value
def public_method(self):
return self._helper_method() # Using protected method
class SubClass(BaseClass):
def use_protected(self):
# ā
DO: Use protected members in subclasses
return self._helper_method()
def override_helper(self):
# ā
DO: Override protected methods
self._value = 10
return "Overridden"
# ā
DO: Use protected for methods subclasses should override
# ā
DO: Use protected for helpers that subclasses need
# ā DON'T: Expose protected members in the public API
# ============================================================
# 3. PRIVATE ā For Implementation Details
# ============================================================
class DataProcessor:
def __init__(self, data):
self._data = data
self.__cache = {} # Private ā caching implementation
self.__processing_count = 0 # Private ā state tracking
def process(self):
"""Public API ā stable and documented"""
self.__processing_count += 1
return self.__process_data()
def __process_data(self):
"""Private ā implementation detail"""
if not self.__cache:
self.__cache = self._build_cache()
return self.__cache
def _build_cache(self):
"""Protected ā can be overridden by subclasses"""
return {"processed": True}
# ā
DO: Use private for implementation details
# ā
DO: Use private for state that shouldn't change
# ā
DO: Use private for methods that might be removed
# ā DON'T: Make everything private
# ============================================================
# 4. GETTERS AND SETTERS (Property Decorator)
# ============================================================
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
self._fahrenheit = celsius * 9/5 + 32
@property
def celsius(self):
"""Getter ā public access"""
return self._celsius
@celsius.setter
def celsius(self, value):
"""Setter ā with validation"""
if value < -273.15:
raise ValueError("Temperature below absolute zero!")
self._celsius = value
self._fahrenheit = value * 9/5 + 32
@property
def fahrenheit(self):
"""Getter ā computed property"""
return self._fahrenheit
@fahrenheit.setter
def fahrenheit(self, value):
self.celsius = (value - 32) * 5/9
# ā
DO: Use properties for controlled access
# ā
DO: Add validation in setters
# ā
DO: Keep the internal representation private (_celsius)
# ============================================================
# 5. SUMMARY TABLE
# ============================================================
print("""
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
ā ACCESS MODIFIER BEST PRACTICES ā
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā£
ā ā
ā PUBLIC (name) ā
ā ⢠Use for the public API of your class ā
ā ⢠Document these well ā
ā ⢠Keep them stable ā avoid breaking changes ā
ā ⢠This is what users of your class interact with ā
ā ā
ā PROTECTED (_name) ā
ā ⢠Use for internal helpers that subclasses might need ā
ā ⢠Use for methods that subclasses should override ā
ā ⢠Use for attributes that subclasses need access to ā
ā ⢠Document that these are for internal use ā
ā ā
ā PRIVATE (__name) ā
ā ⢠Use for implementation details that should be hidden ā
ā ⢠Use for sensitive data (passwords, tokens, etc.) ā
ā ⢠Use for internal state that should not be accessed ā
ā ⢠Use for methods that might be removed or changed ā
ā ā
ā REMEMBER: ā
ā ⢠Protected and private are CONVENTIONS, not security ā
ā ⢠Python trusts developers to respect the conventions ā
ā ⢠Private uses name mangling to prevent accidental access ā
ā ā
ā āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā£
ā "We're all consenting adults here." ā Python Philosophy ā
āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
""")
Best practices summary:
- Public ā the stable API, document well, avoid breaking changes
- Protected ā for subclasses, internal helpers, override points
- Private ā implementation details, sensitive data, can change
- Properties ā use
@propertyfor controlled access - Remember ā these are conventions, not security walls
Quick Check: What should you use protected members for? (Answer: Internal helpers that subclasses might need or override)
Try It Yourself
Experiment with access modifiers in the editor below.
ACCESS MODIFIERS - PRACTICE
==================================================
1. CLASS WITH PUBLIC, PROTECTED, PRIVATE
2. USING THE BANK ACCOUNT
ā Deposited $500. Balance: $1500
ā Withdrew $200. Balance: $1300
Balance: $1300
Transactions: ['Deposit: +$500', 'Withdrawal: -$200']
3. ACCESSING PROTECTED AND PRIVATE
Protected _type: savings (accessible but discouraged)
ā Cannot access __balance: 'BankAccount' object has no attribute '__balance'
Name mangling: 1300 (hack)
4. SUBCLASS (SAVINGS ACCOUNT)
š° Interest applied: $50.00
Balance: $2050.0
==================================================
SUMMARY:
ā Public: owner, deposit(), withdraw(), get_balance()
ā Protected: _type, _add_transaction()
ā Private: __balance, __transactions, __calculate_interest()
ā Name mangling: _BankAccount__balance
==================================================
You've Got It!
You now understand public, private, and protected access modifiers in Python. You know how to use underscores for visibility control and how name mangling works.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
Does Python have public, private, and protected like Java?
_name), and private uses a double underscore (__name). However, these are not enforced ā they're signals to other developers.
Can I access a private member from outside the class?
_ClassName__name. You can access them using the mangled name, but you shouldn't. This is considered a hack and violates the encapsulation principle.
What's the difference between protected and private?
_name) is a convention for "internal use, but subclasses can access it." Private (__name) uses name mangling and is harder to access from outside the class. Private members are not accessible in subclasses.
When should I use protected vs private?
Why doesn't Python enforce access modifiers?
What is the purpose of name mangling?
Where to Go From Here
Now that you understand access modifiers in Python, check out these related topics:
Encapsulation in Python
Learn more about encapsulating data and implementation details.
Learn More āInheritance in Python
Learn how protected members work with inheritance hierarchies.
Learn More āProperty Decorator
Learn how to use @property for controlled attribute access.
Learn More ā