f | SPOOKY_PREFIX = "spooky_" | f | SPOOKY_PREFIX = "spooky_" |
| | | |
| class HauntedMansion: | | class HauntedMansion: |
| def __init__(self, **kwargs): | | def __init__(self, **kwargs): |
| for attribute_name, value in kwargs.items(): | | for attribute_name, value in kwargs.items(): |
| setattr(self, attribute_name, value) | | setattr(self, attribute_name, value) |
| | | |
| def __getattr__(self, attribute_name): | | def __getattr__(self, attribute_name): |
| return "Booooo, only ghosts here!" | | return "Booooo, only ghosts here!" |
| | | |
| def __setattr__(self, attribute_name, value): | | def __setattr__(self, attribute_name, value): |
| attribute_name = SPOOKY_PREFIX + attribute_name | | attribute_name = SPOOKY_PREFIX + attribute_name |
| super().__setattr__(attribute_name, value) | | super().__setattr__(attribute_name, value) |
t | | t | |
| haunted_mansion = HauntedMansion(butler="Alfred", rooms=10, basement=True) | | |
| | | |
| # Опитваме се да достъпим стандартни имена на атрибути | | |
| print(haunted_mansion.butler) # Извежда: Booooo, only ghosts here! | | |
| | | |
| print(haunted_mansion.spooky_butler) # Извежда: Alfred | | |
| | | |
| # Динамично добавяне на нов атрибут | | |
| haunted_mansion.friendly_ghost = "Your favourite HP ghost - Nearly Headless Nick" | | |
| print(haunted_mansion.friendly_gho) # Извежда: Booooo, only ghosts here! | | |
| | | |
| #if attribute_name[:SPOOKY_PREFIX_LENGTH] == SPOOKY_PREFIX: | | |
| # return getattr(self, attribute_name) | | |