📦 Access Specifiers in Python
Public, Protected & Private Members
🔹 DefinitionAccess specifiers in Python are used to control how and where class variables and methods can be accessed. In simple words, they decide who is allowed to see or use the data of a class.
They are mainly used to protect data from being changed accidentally and to maintain proper structure in object-oriented programming. Python does not enforce access specifiers strictly like some other languages, but it follows naming conventions that developers respect while writing code.
📌 Syntax
Python uses underscores to define access specifiers:
- Public → variable
- Protected → _variable
- Private → __variable
There are no special keywords; only naming rules are followed.
📂 Types of Access Specifiers with Examples
1️⃣ Public Access Specifier
DefinitionPublic members are accessible from anywhere, inside or outside the class.
Example
class Student:
def __init__(self, name):
self.name = name
def show_name(self):
print(self.name)
obj = Student("Rahul")
print(obj.name)
obj.show_name()
Here, name and show_name() are public. They can be accessed freely using the object. Public access is used when data is safe and meant to be shared.
2️⃣ Protected Access Specifier
DefinitionProtected members are meant to be accessed within the class and its child classes.
Example
class Student:
def __init__(self):
self._school = "ABC School"
class Child(Student):
def show_school(self):
print(self._school)
obj = Child()
obj.show_school()
The single underscore tells developers that this data should not be used outside unless necessary. It provides a soft level of protection.
3️⃣ Private Access Specifier
DefinitionPrivate members are restricted to the same class only.
Example
class Student:
def __init__(self):
self.__roll = 10
def show_roll(self):
print(self.__roll)
obj = Student()
obj.show_roll()
The double underscore hides the variable using name mangling, making direct access impossible. This is useful when data must be fully protected.
🔑 Conclusion
Access specifiers help in data security, clarity, and better code design. Even though Python relies on conventions, they are very important in real-world programming.
📌 Key Points to Remember
- Public members can be accessed from anywhere
- Protected members use a single underscore
- Private members use double underscore
- Python follows conventions, not strict rules