Access Control Techniques
Overview of Attribute Access Control
Python offers multiple techniques to restrict and manage attribute access, providing developers with fine-grained control over object interactions.
slots Mechanism
class OptimizedUser:
__slots__ = ['name', 'age']
def __init__(self, name, age):
self.name = name
self.age = age
Access Control Techniques Comparison
Technique |
Purpose |
Performance |
Flexibility |
slots |
Memory Optimization |
High |
Low |
@property |
Validation & Computed Properties |
Medium |
High |
getattr |
Dynamic Attribute Handling |
Medium |
Very High |
Descriptors |
Advanced Attribute Management |
Low |
Very High |
getattr and setattr Methods
class SecureConfig:
def __init__(self):
self._data = {}
def __getattr__(self, name):
if name not in self._data:
raise AttributeError(f"'{name}' not configured")
return self._data[name]
def __setattr__(self, name, value):
if name.startswith('_'):
super().__setattr__(name, value)
else:
self._data[name] = value
Descriptor Protocol
class ValidatedAttribute:
def __init__(self, validator):
self.validator = validator
self.data = {}
def __get__(self, instance, owner):
return self.data.get(instance, None)
def __set__(self, instance, value):
if not self.validator(value):
raise ValueError("Invalid value")
self.data[instance] = value
class Person:
age = ValidatedAttribute(lambda x: 0 <= x <= 120)
Access Control Flow
graph TD
A[Attribute Access] --> B{Control Mechanism}
B --> |__slots__| C[Memory Optimization]
B --> |@property| D[Validation]
B --> |__getattr__| E[Dynamic Handling]
B --> |Descriptors| F[Advanced Management]
Advanced Techniques
1. Private Attributes
class SecureClass:
def __init__(self):
self.__private_attr = 42 ## Name mangling
2. Read-Only Properties
class Configuration:
@property
def readonly_setting(self):
return self._internal_setting
- Minimize runtime overhead
- Choose technique based on specific requirements
- Balance between flexibility and performance
Practical Recommendations
- Use @property for simple validations
- Employ slots for memory-critical classes
- Leverage descriptors for complex attribute management
- Implement getattr for dynamic attribute handling
LabEx encourages developers to understand and apply these techniques judiciously to create robust and efficient Python code.