Предизвикателства > Haunted mansion > Решения > Решението на Виктор Бечев

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

1 точки общо

1 успешни теста
0 неуспешни теста
Код

 1"""An alternative solution with __getattribute__, instead of __setattr__."""
 2
 3
 4class HauntedMansion:
 5    SPOOKY_PREFIX = 'spooky_'
 6
 7    def __init__(self, **kwargs):
 8        for key, value in kwargs.items():
 9            setattr(self, key, value)
10
11    def __getattribute__(self, name):
12        if name.startswith('__'):
13            return super().__getattribute__(name)
14        if name.startswith(HauntedMansion.SPOOKY_PREFIX):
15            actual_name = name[len(HauntedMansion.SPOOKY_PREFIX):]
16            return super().__getattribute__(actual_name)
17        raise AttributeError
18
19    def __getattr__(self, name):
20        return "Booooo, only ghosts here!"

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

OK

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

f1"""An alternative solution with __getattribute__, instead of __setattr__."""f1"""An alternative solution with __getattribute__, instead of __setattr__."""
tt2 
23
3class HauntedMansion:4class HauntedMansion:
4    SPOOKY_PREFIX = 'spooky_'5    SPOOKY_PREFIX = 'spooky_'
56
6    def __init__(self, **kwargs):7    def __init__(self, **kwargs):
7        for key, value in kwargs.items():8        for key, value in kwargs.items():
8            setattr(self, key, value)9            setattr(self, key, value)
910
10    def __getattribute__(self, name):11    def __getattribute__(self, name):
11        if name.startswith('__'):12        if name.startswith('__'):
12            return super().__getattribute__(name)13            return super().__getattribute__(name)
13        if name.startswith(HauntedMansion.SPOOKY_PREFIX):14        if name.startswith(HauntedMansion.SPOOKY_PREFIX):
14            actual_name = name[len(HauntedMansion.SPOOKY_PREFIX):]15            actual_name = name[len(HauntedMansion.SPOOKY_PREFIX):]
15            return super().__getattribute__(actual_name)16            return super().__getattribute__(actual_name)
16        raise AttributeError17        raise AttributeError
1718
18    def __getattr__(self, name):19    def __getattr__(self, name):
19        return "Booooo, only ghosts here!"20        return "Booooo, only ghosts here!"
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op