Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python - Access Modifiers (Complete Guide for Beginners)

 In Object-Oriented Programming (OOP), Access Modifiers control how attributes and methods of a class can be accessed. They help protect data and prevent accidental modifications.

Unlike some programming languages such as Java and C++, Python does not have strict access modifiers. Instead, Python uses naming conventions to indicate whether members should be public, protected, or private.

In this tutorial, you will learn how access modifiers work in Python with practical examples.


What are Access Modifiers?

Access modifiers determine the visibility and accessibility of:

  • Variables (Attributes)
  • Methods (Functions)

They help achieve Encapsulation, one of the four pillars of OOP.


Types of Access Modifiers in Python

Python provides three access levels:

Access ModifierSyntaxAccessible
PublicnameEverywhere
Protected_nameClass and subclasses
Private__nameWithin class only

1. Public Access Modifier

Public members can be accessed from anywhere.

Example

class Student:

    def __init__(self):
        self.name = "John"

student = Student()

print(student.name)

Output

John

How Public Members Work

Public variables and methods:

  • Can be accessed inside the class
  • Can be accessed outside the class
  • Can be modified directly

Example

class Car:

    def __init__(self):
        self.brand = "Toyota"

car = Car()

print(car.brand)

car.brand = "Honda"

print(car.brand)

Output

Toyota
Honda

Public Methods

Example

class Employee:

    def display(self):
        print("Employee Information")

emp = Employee()

emp.display()

2. Protected Access Modifier

Protected members use a single underscore (_) prefix.

Syntax

_variable

Protected members are intended for:

  • The class itself
  • Child classes (subclasses)

Protected Variable Example

class Person:

    def __init__(self):
        self._name = "Alice"

person = Person()

print(person._name)

Output

Alice

Although accessible, the underscore indicates:

"This variable is intended for internal use."


Protected Member with Inheritance

Example

class Animal:

    def __init__(self):
        self._sound = "Animal Sound"

class Dog(Animal):

    def display(self):
        print(self._sound)

dog = Dog()

dog.display()

Output

Animal Sound

Protected Methods

Example

class Vehicle:

    def _start_engine(self):
        print("Engine Started")

class Car(Vehicle):

    def run(self):
        self._start_engine()

car = Car()

car.run()

3. Private Access Modifier

Private members use double underscores (__) before the name.

Syntax

__variable

Private members are designed to be accessed only inside the class.


Private Variable Example

class BankAccount:

    def __init__(self):
        self.__balance = 1000

account = BankAccount()

# print(account.__balance)

Output

AttributeError

Python prevents direct access to private variables.


Accessing Private Variables Using Methods

Example

class BankAccount:

    def __init__(self):
        self.__balance = 1000

    def get_balance(self):
        return self.__balance

account = BankAccount()

print(account.get_balance())

Output

1000

Private Methods

Example

class Security:

    def __verify(self):
        print("Verification Successful")

    def login(self):
        self.__verify()

s = Security()

s.login()

Output

Verification Successful

Name Mangling in Python

Python uses a mechanism called Name Mangling for private members.

Example

class Test:

    def __init__(self):
        self.__value = 10

obj = Test()

print(obj._Test__value)

Output

10

Although possible, this technique should generally be avoided.


Real-World Example: Banking System

class BankAccount:

    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

account = BankAccount("John", 5000)

account.deposit(1000)

print(account.get_balance())

Output

6000

Real-World Example: Employee Management

class Employee:

    company = "Tech Corp"

    def __init__(self, name, salary):
        self.name = name
        self._department = "IT"
        self.__salary = salary

    def get_salary(self):
        return self.__salary

employee = Employee("Alice", 5000)

print(employee.name)
print(employee._department)
print(employee.get_salary())

Comparison of Access Modifiers

ModifierSymbolAccessible in ClassAccessible in Child ClassAccessible Outside
PublicNoneYesYesYes
Protected_YesYesYes*
Private__YesNoNo

*Protected members can still be accessed outside the class, but it is discouraged.


Access Modifiers and Encapsulation

Access modifiers help implement encapsulation by:

  • Protecting sensitive data
  • Restricting direct access
  • Providing controlled access through methods

Example

class User:

    def __init__(self):
        self.__password = "secret123"

    def get_password(self):
        return "Access Denied"

user = User()

print(user.get_password())

Common Mistakes

Mistake 1: Accessing Private Variable Directly

❌ Wrong

account.__balance

✔ Correct

account.get_balance()

Mistake 2: Assuming Protected Means Private

❌ Wrong

obj._name

Protected variables can still be accessed.


Mistake 3: Overusing Private Members

Making everything private can make code difficult to maintain.

Use private members only when necessary.


Best Practices

  • Use public members for general access.
  • Use protected members for inheritance-related features.
  • Use private members for sensitive data.
  • Provide getter and setter methods when needed.
  • Follow Python naming conventions consistently.

Practical Example: Student Record System

class Student:

    def __init__(self, name, grade):
        self.name = name
        self._course = "Python"
        self.__grade = grade

    def get_grade(self):
        return self.__grade

student = Student("John", "A")

print(student.name)
print(student._course)
print(student.get_grade())

Summary

ModifierPrefixPurpose
PublicNoneOpen access
Protected_Internal use and inheritance
Private__Restricted access

Conclusion

Access modifiers are an important part of Python OOP and help organize, protect, and manage class data effectively.

You learned:

  • What access modifiers are
  • Public, protected, and private members
  • How encapsulation works
  • Name mangling
  • Real-world examples
  • Best practices

Understanding access modifiers will help you build secure, maintainable, and professional Python applications.


Practice Exercises

Exercise 1

Create a Student class with:

  • Public variable name
  • Protected variable _course
  • Private variable __marks

Display all values using appropriate methods.


Exercise 2

Create a BankAccount class with:

  • Public owner name
  • Private balance

Add methods for deposit and checking balance.


Exercise 3

Create a Vehicle class with a protected method and access it from a child class.




Post a Comment

0 Comments