Attribute Visibility Basics
Understanding Attribute Visibility in Python
In Python, attribute visibility refers to the accessibility and control of class attributes from different contexts. Unlike some programming languages with strict access modifiers, Python provides a more flexible approach to managing attribute visibility.
Visibility Types in Python
Python supports three primary levels of attribute visibility:
Visibility Level |
Naming Convention |
Accessibility |
Public Attributes |
attribute_name |
Fully accessible from anywhere |
Protected Attributes |
_attribute_name |
Intended for internal use |
Private Attributes |
__attribute_name |
Strongly restricted access |
Public Attributes
Public attributes are the default in Python. They can be freely accessed and modified from anywhere in the code.
class Person:
def __init__(self, name):
self.name = name ## Public attribute
person = Person("Alice")
print(person.name) ## Accessible directly
Protected Attributes
Protected attributes use a single underscore prefix, indicating they are intended for internal use within a class or its subclasses.
class Employee:
def __init__(self, name, salary):
self.name = name ## Public attribute
self._salary = salary ## Protected attribute
def get_salary(self):
return self._salary
Private Attributes
Private attributes use double underscore prefix, providing name mangling to restrict direct access.
class BankAccount:
def __init__(self, balance):
self.__balance = balance ## Private attribute
def get_balance(self):
return self.__balance
Visibility Flow Diagram
graph TD
A[Public Attribute] --> |Fully Accessible| B[Any Context]
C[Protected Attribute] --> |Discouraged External Access| D[Class and Subclasses]
E[Private Attribute] --> |Strongly Restricted| F[Original Class Only]
Best Practices
- Use public attributes for general, unrestricted access
- Use protected attributes for internal implementation details
- Use private attributes for sensitive data that should not be directly modified
By understanding these visibility mechanisms, developers can create more robust and encapsulated class designs in Python. LabEx recommends practicing these concepts to improve your object-oriented programming skills.