Access Modifiers in Python define the visibility and accessibility of class attributes and methods.
Unlike some other languages (like Java or C++), Python relies more on conventions than strict enforcement.
Python provides three main types of access modifiers to manage the visibility of class attributes and methods:
- Public: Accessible from anywhere (default).
- Private: Accessible only within the class. Indicated by
__. - Protected: Meant to be accessed within the class and its subclasses. Indicated by
_.
Example: Public Access
class Student:
def __init__(self, age, name):
self.age = age # Public variable
self.name = name # Public variable
obj = Student(21, "John")
print(obj.age) # Output: 21
print(obj.name) # Output: JohnExample: Private Access
class Student:
def __init__(self, age, name):
self.__age = age # Private variable
obj = Student(21, "John")
# This will raise an error
print(obj.__age) # AttributeErrorExample: Protected Access
class Student:
def __init__(self):
self._name = "John" # Protected variable
class Subject(Student):
pass
obj = Student()
print(obj._name) # Output: JohnBest Practices
- Use public attributes for general data.
- Use private attributes (
__) for sensitive data you don’t want accessed directly. - Use protected attributes (
_) when you expect subclasses to use them.
👉 Next tutorial: Python Static Methods