Access modifiers in Python control the accessibility of class members (attributes and methods). Although Python doesn’t have traditional access modifiers like some other programming languages, it uses naming conventions to indicate the intended accessibility. Understanding Python’s access modifiers helps you write more secure and maintainable code. This tutorial covers everything you need to know about access modifiers in Python, including examples, explanations, and best practices.
Access modifiers in Python are a way to specify the visibility and accessibility of class members (attributes and methods). By using specific naming conventions, Python developers can indicate the intended access level of these members, helping to protect sensitive data and enforce encapsulation principles.
Access modifiers help:
In Python, access levels are indicated by name prefixes. There are three main types of access modifiers:
class Car:
def __init__(self, brand, model):
self.brand = brand # Public attribute
self.model = model # Public attribute
def display_info(self): # Public method
return f"Car: {self.brand} {self.model}"
# Accessing public members
car = Car("Toyota", "Camry")
print(car.brand) # Output: Toyota
print(car.display_info()) # Output: Car: Toyota Camry
_
.class Car:
def __init__(self, brand, model):
self._brand = brand # Protected attribute
def _display_brand(self): # Protected method
return f"Brand: {self._brand}"
# Accessing protected members
car = Car("Toyota", "Camry")
print(car._brand) # Output: Toyota (although discouraged)
print(car._display_brand()) # Output: Brand: Toyota (although discouraged)
__
.class Car:
def __init__(self, brand, model):
self.__engine_number = "123ABC" # Private attribute
def __display_engine_number(self): # Private method
return f"Engine Number: {self.__engine_number}"
def get_engine_info(self): # Public method to access private member
return self.__display_engine_number()
car = Car("Toyota", "Camry")
print(car.get_engine_info()) # Output: Engine Number: 123ABC
car.__engine_number
or car.__display_engine_number()
from outside the class would raise an AttributeError
.Public members are the default access level in Python and are accessible from anywhere.
class Book:
def __init__(self, title, author):
self.title = title # Public attribute
self.author = author # Public attribute
def get_book_info(self): # Public method
return f"Title: {self.title}, Author: {self.author}"
book = Book("1984", "George Orwell")
print(book.title) # Output: 1984
print(book.get_book_info()) # Output: Title: 1984, Author: George Orwell
Protected members are used when an attribute or method is meant to be accessed only within the class or subclasses. Although technically accessible from outside, it’s discouraged.
class Employee:
def __init__(self, name, salary):
self._salary = salary # Protected attribute
def _get_salary(self): # Protected method
return f"Salary: {self._salary}"
# Accessing protected members from a subclass
class Manager(Employee):
def display_salary(self):
return f"Manager's {self._get_salary()}"
manager = Manager("Alice", 75000)
print(manager.display_salary()) # Output: Manager's Salary: 75000
self._salary
and self._get_salary()
are protected members intended to be accessed only within Employee
and its subclasses.Private members restrict access, making attributes and methods accessible only within the class itself. This prevents accidental modifications from outside.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance # Private attribute
def __get_balance(self): # Private method
return f"Balance: ${self.__balance}"
def display_account_info(self):
return f"Owner: {self.owner}, {self.__get_balance()}"
account = BankAccount("John Doe", 1000)
print(account.display_account_info()) # Output: Owner: John Doe, Balance: $1000
__balance
attribute and __get_balance
method are private, accessible only within BankAccount
.account.__balance
directly would raise an AttributeError
.When inheriting, protected members are accessible within subclasses, but private members are not.
class Animal:
def __init__(self, name):
self._name = name # Protected attribute
self.__species = "Unknown" # Private attribute
class Dog(Animal):
def display_name(self):
return f"Dog's name: {self._name}"
def display_species(self):
# Trying to access private attribute
return f"Species: {self.__species}" # Raises AttributeError
dog = Dog("Buddy")
print(dog.display_name()) # Output: Dog's name: Buddy
# print(dog.display_species()) # Raises AttributeError
_name
attribute is accessible in the Dog
subclass.__species
attribute cannot be accessed in Dog
, as it’s private to Animal
._
for protected, __
for private) to indicate intended accessibility.class User:
def __init__(self, username, password):
self.username = username
self.__password = password # Private attribute
def verify_password(self, input_password):
return self.__password == input_password
user = User("john_doe", "securepassword123")
print(user.verify_password("securepassword123")) # Output: True
# print(user.__password) # Raises AttributeError
__password
attribute is private, ensuring sensitive information is hidden.class Vehicle:
def __init__(self, make, model):
self._make = make # Protected attribute
self._model = model # Protected attribute
class Car(Vehicle):
def get_info(self):
return f"Car: {self._make} {self._model}"
car = Car("Toyota", "Camry")
print(car.get_info()) # Output: Car: Toyota Camry
_make
and _model
attributes are protected, intended for use within Vehicle
and its subclasses like Car
._
and intended for internal or subclass use.__
and accessible only within the class.Access modifiers in Python help manage the visibility of class attributes and methods, ensuring that only authorized code can access or modify certain members. Although Python doesn’t have traditional access modifiers, it uses naming conventions to indicate public, protected, and private access levels. By following best practices, such as encapsulating sensitive data and using public methods for interfaces, you can write secure, maintainable, and well-organized code.
With Python access modifiers, you can:
Ready to implement access modifiers in your Python classes? Practice using public, protected, and private members to see how they improve code security and organization. Happy coding!