Предизвикателства > Haunted mansion > Решения > Решението на Ивана Димитрова

Резултати
1 точки от тестове
0 точки от учител

1 точки общо

1 успешни теста
0 неуспешни теста
Код (Решението без принтене)

 1SPOOKY_PREFIX = "spooky_"
 2
 3class HauntedMansion:
 4    def __init__(self, **kwargs):
 5        for attribute_name, value in kwargs.items():
 6            setattr(self, attribute_name, value)
 7    
 8    def __getattr__(self, attribute_name):
 9        return "Booooo, only ghosts here!"
10    
11    def __setattr__(self, attribute_name, value):
12        attribute_name = SPOOKY_PREFIX + attribute_name
13        super().__setattr__(attribute_name, value)

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Дискусия
История

f1SPOOKY_PREFIX = "spooky_"f1SPOOKY_PREFIX = "spooky_"
22
3class HauntedMansion:3class HauntedMansion:
4    def __init__(self, **kwargs):4    def __init__(self, **kwargs):
5        for attribute_name, value in kwargs.items():5        for attribute_name, value in kwargs.items():
6            setattr(self, attribute_name, value)6            setattr(self, attribute_name, value)
7    7    
8    def __getattr__(self, attribute_name):8    def __getattr__(self, attribute_name):
9        return "Booooo, only ghosts here!"9        return "Booooo, only ghosts here!"
10    10    
11    def __setattr__(self, attribute_name, value):11    def __setattr__(self, attribute_name, value):
12        attribute_name = SPOOKY_PREFIX + attribute_name12        attribute_name = SPOOKY_PREFIX + attribute_name
13        super().__setattr__(attribute_name, value)13        super().__setattr__(attribute_name, value)
t14 t
15haunted_mansion = HauntedMansion(butler="Alfred", rooms=10, basement=True)
16 
17# Опитваме се да достъпим стандартни имена на атрибути
18print(haunted_mansion.butler)  # Извежда: Booooo, only ghosts here!
19 
20print(haunted_mansion.spooky_butler)  # Извежда: Alfred
21 
22# Динамично добавяне на нов атрибут
23haunted_mansion.friendly_ghost = "Your favourite HP ghost - Nearly Headless Nick"
24print(haunted_mansion.friendly_gho)  # Извежда: Booooo, only ghosts here!
25 
26#if attribute_name[:SPOOKY_PREFIX_LENGTH] == SPOOKY_PREFIX:
27         #   return getattr(self, attribute_name)
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op