🧱 Python Object-Oriented Programming (OOP)
Estimated reading: 3 minutes 23 views

πŸ” Python Access Modifiers – Public, Protected, Private Explained

🧲 Introduction – Why Access Modifiers Matter

In object-oriented programming, encapsulation is the practice of restricting direct access to some components of an object, which is essential for maintaining data integrity and security. Although Python doesn’t enforce access restrictions like Java or C++, it provides naming conventions and name mangling to achieve similar functionality.

In this guide, you’ll learn:

  • πŸ“˜ The types of access modifiers in Python
  • πŸ” How naming conventions influence access
  • πŸ”’ Real-world examples using private and protected members
  • 🧠 Best practices for encapsulation in Python

πŸ”‘ Access Modifier Types in Python

Python provides three levels of access control using naming conventions:

ModifierSyntax ExampleDescription
Publicself.nameAccessible from anywhere.
Protectedself._nameMeant for internal use (not enforced). Accessible in subclasses.
Privateself.__nameName-mangled. Not directly accessible outside the class.

πŸ§ͺ Public Members

class Student:
    def __init__(self, name):
        self.name = name  # public attribute

βœ… Explanation:

  • self.name is a public attribute.
  • Can be accessed and modified freely: student.name = "Alice"

πŸ” Protected Members

class Student:
    def __init__(self, name):
        self._name = name  # protected attribute

class Graduate(Student):
    def display(self):
        print("Name:", self._name)

βœ… Explanation:

  • _name is a protected member.
  • Can be accessed in subclasses but by convention shouldn’t be accessed directly outside.

πŸ’‘ Tip: Use _attribute to indicate it’s intended for internal use only.


πŸ”’ Private Members with Name Mangling

class Student:
    def __init__(self, name):
        self.__name = name  # private attribute

    def get_name(self):
        return self.__name

βœ… Explanation:

  • __name is a private member.
  • Python automatically changes __name to _Student__name (name mangling).
  • Access: student._Student__name (not recommended).

⚠️ Warning: Private attributes are still accessible using mangled names. Python’s privacy is by convention, not enforced.


πŸ”„ Accessing Private Members (Name Mangling Example)

student = Student("Bob")
print(student._Student__name)  # Output: Bob

⚠️ Note: Avoid this approach in production. Use getters/setters instead.


🧠 Encapsulation Best Practices

PracticeDescription
Use __attribute for private accessPrevents accidental access or override in subclasses
Use _attribute for protected accessIndicates internal usage (e.g., during inheritance)
Use public methods for accessDefine get_ and set_ methods to control read/write access

🧰 Real-World Example

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

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

    def get_balance(self):
        return self.__balance

πŸ” This class:

  • Hides the balance using __balance
  • Allows safe modification via deposit()
  • Prevents external tampering

πŸ“Œ Summary – Recap & Next Steps

Python’s access modifiers rely on conventions rather than strict syntax rules. By using naming conventions such as _ and __, developers can enforce encapsulation and prevent accidental misuse of class internals.

πŸ” Key Takeaways:

  • self.name is public
  • self._name is protected (by convention)
  • self.__name is private (via name mangling)
  • Access private attributes using getters/setters for safety

βš™οΈ Real-World Relevance: Encapsulation ensures robust, modular, and maintainable Python applications, especially in large codebases and collaborative projects.


❓ FAQ – Python Access Modifiers

❓ What is the purpose of access modifiers in Python?

βœ… They help control access to class members, supporting encapsulation and maintaining object integrity.

❓ Are access modifiers enforced in Python?

❌ No, Python uses convention-based access. Even private attributes can be accessed externally via name mangling.

❓ How do I declare a private attribute?

βœ… Use double underscores: self.__myvar. Python mangles it to _ClassName__myvar.

❓ What is the difference between _var and __var?

βœ… _var: Protected (by convention), accessible in subclass
βœ… __var: Private (via name mangling), hidden from subclass and external access

❓ Can I access a private variable from outside the class?

βœ… Technically yes, using _ClassName__var, but it’s not recommended.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Access Modifiers

Or Copy Link

CONTENTS
Scroll to Top