Предизвикателства > Haunted mansion > Решения > Решението на Стефан Шиваров

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

1 точки общо

1 успешни теста
0 неуспешни теста
Код
Скрий всички коментари

 1class HauntedMansion:
 2    """A class with attributes accessible only through a spooky prefix."""
 3
 4    _ATTR_PREFIX = "spooky_"
 5
 6    def __init__(self, **kwargs):
 7        """Initialize with keyword arguments as attributes."""
 8        for key, value in kwargs.items():
 9            setattr(self, key, value)
10
11    def __getattribute__(self, name):
12        """
13        Retrieve the value of an attribute if it is spooky-prefixed.
14
15        If not prefixed, return a spooky message instead.
16        """
17        if name.startswith(HauntedMansion._ATTR_PREFIX):
18            actual_attribute_name = name[len(HauntedMansion._ATTR_PREFIX):]
19
20            if actual_attribute_name in object.__getattribute__(
21                    self, "__dict__"):
22                return object.__getattribute__(self, actual_attribute_name)
23            elif actual_attribute_name in object.__getattribute__(
24                    self.__class__, "__dict__"):
25                return object.__getattribute__(
26                    self.__class__, actual_attribute_name)
27
28        if (name.startswith("__") and
29                name.endswith("__") and
30                name in dir(HauntedMansion)):
31            return object.__getattribute__(self, name)
32
33        return "Booooo, only ghosts here!"

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

OK

Дискусия
История
Това решение има само една версия.