- Learning Objectives
- Prerequisites
- Introduction
- What are Access Specifiers?
- Why are Access Specifiers Required?
- Types of Access Specifiers
- Public Members
- Protected Members
- Private Members
- Name Mangling
- Comparison of Access Specifiers
- Internal Working
- Advantages
- Summary
After completing this chapter, you will be able to:
- Understand Access Specifiers.
- Explain the need for Access Specifiers.
- Learn Public, Protected, and Private members.
- Understand Name Mangling.
- Apply Access Specifiers in real-world applications.
- Differentiate Python and Java access control.
Before learning this chapter, you should know:
- Classes
- Objects
- Encapsulation
- Instance Variables
- Methods
- Inheritance
In the previous chapter, we learned Encapsulation, which combines data and methods into a single unit while protecting data from unauthorized access.
One important concept used to implement Encapsulation is Access Specifiers.
Access Specifiers determine who can access class variables and methods.
Unlike Java or C++, Python does not enforce strict access modifiers. Instead, it uses naming conventions that developers follow to indicate how members should be accessed.
Access Specifiers are mechanisms used to control the visibility and accessibility of class members (variables and methods).
They help protect data and support Encapsulation.
Access Specifiers decide who can access the members of a class.
Consider a Banking Application.
A Bank Account contains:
- Account Number
- Customer Name
- Balance
- ATM PIN
Can every user directly modify the balance or PIN?
No.
Instead,
the application should allow access only through methods such as
- Deposit()
- Withdraw()
- ChangePIN()
This prevents unauthorized modifications.
Consider a Hospital Management System.
Doctor Information
Doctor Name
Department
Salary
Password
Everyone can know the doctor's name and department.
However,
Salary and Password should be protected.
Access Specifiers help implement this restriction.
Python provides three types of Access Specifiers.
- Public
- Protected
- Private
Public members can be accessed from anywhere.
They can be accessed:
- Inside the class
- Outside the class
- Inside child classes
No special symbol is required.
variable
method()Example
class Student:
def __init__(self):
self.name = "Rahul"Here,
nameis a Public Variable.
Protected members are intended to be accessed only inside the class and its child classes.
Python represents Protected members using a single underscore.
_variableExample
self._marks = 95Although accessible from outside the class, doing so is discouraged by convention.
Private members are intended to be accessed only inside the class where they are declared.
Python represents Private members using two underscores.
__variableExample
self.__password = "Python123"Python internally changes the variable name.
This process is called Name Mangling.
Python does not completely hide private members.
Instead,
it changes
__passwordinto
_Student__passwordThis prevents accidental access.
It is not a security mechanism.
| Access Specifier | Symbol | Same Class | Child Class | Outside Class |
|---|---|---|---|---|
| Public | None | ✅ | ✅ | ✅ |
| Protected | _ |
✅ | ✅ | |
| Private | __ |
✅ | ❌ Direct Access | ❌ Direct Access |
| Java | Python |
|---|---|
| Compiler Enforced | Naming Convention |
| Strict Access Control | Flexible Access Control |
| public | Public |
| protected | _Protected |
| private | __Private |
Suppose
self.__salaryPython internally converts it into
_Employee__salaryWhen accessed outside,
Python searches
__salarywhich does not exist.
Therefore,
an
AttributeError
is generated.
- Supports Encapsulation.
- Protects sensitive information.
- Prevents accidental modification.
- Makes programs easier to maintain.
- Improves code organization.
- Encourages better software design.
Access Specifiers are used in:
- Banking Systems
- ATM Applications
- Employee Management Systems
- Hospital Management Systems
- E-Commerce Applications
- School Management Systems
In this part, we learned:
- Access Specifiers
- Public Members
- Protected Members
- Private Members
- Name Mangling
- Python vs Java Access Control
- Internal Working
- Advantages
Write a Python program to demonstrate Public Members.
class Student:
def __init__(self):
self.name = "Rahul"
student = Student()
print(student.name)Rahul
The variable
nameis a Public Variable.
It can be accessed
- Inside the class
- Outside the class
- Inside child classes
without any restrictions.
Write a Python program to demonstrate Protected Members.
class Student:
def __init__(self):
self._marks = 95
student = Student()
print(student._marks)95
The variable
_marksis a Protected Variable.
Python allows access outside the class,
but according to Python conventions,
Protected members should only be used
- Inside the class
- Inside child classes
Write a Python program to demonstrate Private Members.
class Student:
def __init__(self):
self.__password = "Python123"
student = Student()
print(student.__password)AttributeError:
'Student' object has no attribute '__password'
Python performs Name Mangling.
Internally,
__passwordbecomes
_Student__passwordTherefore,
direct access fails.
Write a Python program to access a private member using Name Mangling.
class Student:
def __init__(self):
self.__password = "Python123"
student = Student()
print(student._Student__password)Python123
Python internally renames
__passwordto
_Student__passwordAlthough this is possible,
it should generally be avoided because it breaks encapsulation.
Write a Python program to demonstrate Protected Members in Inheritance.
class Person:
def __init__(self):
self._name = "Rahul"
class Student(Person):
def display(self):
print(self._name)
student = Student()
student.display()Rahul
Protected members are intended to be inherited.
The child class can directly access
_nameWrite a Python program to demonstrate Private Members in Inheritance.
class Person:
def __init__(self):
self.__salary = 50000
class Employee(Person):
def display(self):
print(self.__salary)
employee = Employee()
employee.display()AttributeError:
'Employee' object has no attribute '_Employee__salary'
Private members are not directly inherited.
Python internally converts
__salaryinto
_Person__salaryInside the child class,
Python searches for
_Employee__salarywhich does not exist.
Hence,
an AttributeError occurs.
class Employee:
def __init__(self):
self.__salary = 50000
def get_salary(self):
return self.__salary
employee = Employee()
print(employee.get_salary())50000
Instead of directly accessing the private variable,
the Getter Method provides controlled access.
This is the recommended approach.
class Employee:
def __init__(self):
self.__salary = 0
def set_salary(self, salary):
if salary > 0:
self.__salary = salary
def get_salary(self):
return self.__salary
employee = Employee()
employee.set_salary(60000)
print(employee.get_salary())60000
The Setter Method validates the data before storing it.
This prevents invalid values from being assigned.
Create Employee Object
↓
Private Variable Created
↓
Getter Called
↓
Private Variable Returned
↓
Output Displayed
Employee Object
│
▼
+------------------------------+
__salary
↓
_Person__salary
↓
50000
------------------------------
get_salary()
set_salary()
+------------------------------+
- Protects sensitive data.
- Prevents accidental modification.
- Supports Encapsulation.
- Improves maintainability.
- Improves code readability.
- Encourages secure programming.
- Use Public members for general-purpose data.
- Use Protected members for inheritance-related data.
- Use Private members for confidential information.
- Prefer Getter and Setter methods instead of Name Mangling.
- Validate data before updating private variables.
Trying to access Private Variables directly.
❌ Incorrect
employee.__salaryProduces
AttributeError
Confusing Protected and Private Members.
_marksis Protected.
__marksis Private.
Using Name Mangling in normal applications.
employee._Employee__salaryAlthough possible,
this should be avoided.
Use Getter methods instead.
Assuming Python provides complete data security.
Python uses naming conventions and Name Mangling.
It is not intended as a strict security mechanism like Java's access modifiers.
Access Specifiers determine the visibility and accessibility of class members.
- Public
- Protected
- Private
No.
Python follows naming conventions instead of compiler-enforced access control.
A member that can be accessed from anywhere.
A member prefixed with a single underscore (_), intended for use within the class and its subclasses.
A member prefixed with a double underscore (__), intended for use only within its own class.
Name Mangling is the process of internally renaming private members to reduce accidental access.
Example:
__salarybecomes
_Employee__salaryNo.
Private members are not directly accessible in child classes.
Using Getter and Setter methods or Python Properties.
| Public | Protected | Private |
|---|---|---|
| Accessible everywhere | Intended for class and subclasses | Intended only for the defining class |
- Create a Student class with Public variables.
- Create an Employee class with Protected variables.
- Create a BankAccount class with Private variables.
- Demonstrate Name Mangling.
- Create Getter and Setter methods.
- Demonstrate Protected Members in Inheritance.
- Demonstrate why Private Members cannot be directly inherited.
- Public → No Prefix
- Protected →
_variable - Private →
__variable - Python follows naming conventions.
- Name Mangling changes the internal name of private members.
- Use Getter and Setter methods for controlled access.
- Access Specifiers help implement Encapsulation.
In this chapter, you learned:
- Access Specifiers
- Public Members
- Protected Members
- Private Members
- Name Mangling
- Inheritance with Access Specifiers
- Getter and Setter Methods
- Practical Programs
- Best Practices
- Common Mistakes
- Interview Questions
- Practice Programs
- Quick Revision