- Published on
2. Access Specifiers in Python
- Authors
2. We know that Python is an object-oriented language, but does it have access specifiers?
🧠 Does Python Have Access Specifiers?
Python does not have traditional access specifiers like public
, private
, and protected
as in C++ or Java. However, it uses naming conventions to indicate the intended level of access.
🔐 Python's Access Specifier Conventions:
Convention | Meaning | Enforced? |
---|---|---|
public | No underscore (var ) | Fully accessible from anywhere |
_protected | Single underscore (_var ) | Suggests internal use only (not enforced) |
__private | Double underscore (__var ) | Name mangling to discourage access |
📌 Examples:
1. Public (Default)
class MyClass:
def __init__(self):
self.value = 42
obj = MyClass()
print(obj.value) # ✅ accessible
2. Protected (Convention Only)
class MyClass:
def __init__(self):
self._internal = "not for external use"
print(obj._internal) # ⚠️ technically allowed, but discouraged
3. Private (Name Mangling)
class MyClass:
def __init__(self):
self.__secret = "hidden"
obj = MyClass()
# print(obj.__secret) # ❌ AttributeError
print(obj._MyClass__secret) # ✅ Works due to name mangling
⚠️ Important:
- These are conventions, not strict rules.
- Python relies on "we're all adults here" philosophy — it trusts the developer.
✅ Summary:
- Python mimics access control using naming conventions.
- No strict enforcement like in Java/C++.
- Use
_
and__
prefixes to indicate intent.