Attribute assignment using __getattr__ and __setattr__ in Python
The __getattr__ method intercepts attribute references and the __setattr__ intercepts all attribute assignments.
class Employee(object): def __init__(self, data): super().__setattr__('data', dict()) self.data = data def __getattr__(self, name): if name in self.data: return self.data[name] else: return 0 def __setattr__(self, key, value): if key in self.data: self.data[key] = value else: super().__setattr__(key, value) emp = Employee({'age': 23, 'name': 'John'}) print(emp.age) print(emp.name) print(emp.data) print(emp.salary) emp.salary = 50000 print(emp.salary)
Sample output of above program.
23 John {'age': 23, 'name': 'John'} 0 50000
2019-07-01T03:00:16+05:30
2019-07-01T03:00:16+05:30
Amit Arora
Amit Arora
Python Programming Tutorial
Python
Practical Solution