f | """An alternative solution with __getattribute__, instead of __setattr__.""" | f | """An alternative solution with __getattribute__, instead of __setattr__.""" |
t | | t | |
| | | |
| class HauntedMansion: | | class HauntedMansion: |
| SPOOKY_PREFIX = 'spooky_' | | SPOOKY_PREFIX = 'spooky_' |
| | | |
| def __init__(self, **kwargs): | | def __init__(self, **kwargs): |
| for key, value in kwargs.items(): | | for key, value in kwargs.items(): |
| setattr(self, key, value) | | setattr(self, key, value) |
| | | |
| def __getattribute__(self, name): | | def __getattribute__(self, name): |
| if name.startswith('__'): | | if name.startswith('__'): |
| return super().__getattribute__(name) | | return super().__getattribute__(name) |
| if name.startswith(HauntedMansion.SPOOKY_PREFIX): | | if name.startswith(HauntedMansion.SPOOKY_PREFIX): |
| actual_name = name[len(HauntedMansion.SPOOKY_PREFIX):] | | actual_name = name[len(HauntedMansion.SPOOKY_PREFIX):] |
| return super().__getattribute__(actual_name) | | return super().__getattribute__(actual_name) |
| raise AttributeError | | raise AttributeError |
| | | |
| def __getattr__(self, name): | | def __getattr__(self, name): |
| return "Booooo, only ghosts here!" | | return "Booooo, only ghosts here!" |