-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass_getitem.py
75 lines (51 loc) · 2.37 KB
/
class_getitem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
'''
Метод __getitem__ визначає, як об'єкт класу повинен вести себе при доступі до його елементів за допомогою індексу або ключа. Він приймає ключ або індекс як аргумент і повинен повертати значення, асоційоване з цим ключем або індексом.
'''
class SimpleDict:
def __init__(self):
self.__data = {}
def __getitem__(self, key):
return self.__data.get(key, "Key not found")
def __setitem__(self, key, value):
self.__data[key] = value
# Використання класу
simple_dict = SimpleDict()
simple_dict['name'] = 'Boris'
print(simple_dict['name'])
print(simple_dict['age'])
#================================================
from collections import UserList
class BoundedList(UserList):
def __init__(self, min_value: int, max_value: int, initial_list=None):
super().__init__(initial_list if initial_list is not None else [])
self.min_value = min_value
self.max_value = max_value
self.__validate_list()
def __validate_list(self):
for item in self.data: # Він використовується для зберігання фактичного списку елементів, які містить BoundedList
self.__validate_item(item)
def __validate_item(self, item):
if not (self.min_value <= item <= self.max_value):
raise ValueError(f"Item {item} must be between {self.min_value} and {self.max_value}")
def append(self, item):
self.__validate_item(item)
super().append(item)
def insert(self, i, item):
self.__validate_item(item)
super().insert(i, item)
def __setitem__(self, i, item):
self.__validate_item(item)
super().__setitem__(i, item)
def __repr__(self):
return f"BoundedList({self.max_value}, {self.min_value})"
def __str__(self):
return str(self.data)
if __name__ == '__main__':
temperatures = BoundedList(18, 26, [19, 21, 22])
print(temperatures) # [19, 21, 22]
for el in [20, 22, 25, 27]:
try:
temperatures.append(el)
except ValueError as e:
print(e) # Item 27 must be between 18 and 26
print(temperatures) # [19, 21, 22, 20, 22, 25]