-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9.1.3.py
More file actions
114 lines (84 loc) · 2.67 KB
/
Copy path9.1.3.py
File metadata and controls
114 lines (84 loc) · 2.67 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""
Напишіть клас TypeDecorators, який має різні методи конвертації результатів
функцій у зазначений тип, якщо це неможливо – викликати відповідний виняток.
Методи:
to_int
to_str
to_bool
to_float
Не забувайте використовувати @wraps
class TypeDecorators:
pass
@TypeDecorators.to_int
def do_nothing(string: str):
return string
@TypeDecorators.to_bool
def do_something(string: str):
return string
assert do_nothing('25') == 25
assert do_something('hello') is True
"""
from functools import wraps
import time
class TypeDecorators:
#----------------------------------------------------------------------
def to_int(f):
@wraps(f)
def wrapper(par):
try:
_result = int(par)
except ValueError:
raise ValueError("input string can not be transform")
else:
return _result
return wrapper
#----------------------------------------------------------------------
def to_str(f):
@wraps(f)
def wrapper(par):
_result=str(par)
print(f"decorator to_str {_result}")
return _result
return wrapper
#----------------------------------------------------------------------
def to_bool(f):
@wraps(f)
def wrapper(par):
try:
_result = par.lower() in ("yes", "true", "t", "1")
except ValueError:
raise ValueError("input string can not be transform")
else:
return _result
return wrapper
#----------------------------------------------------------------------
def to_float(f):
@wraps(f)
def wrapper(par):
try:
_result = float(par)
except ValueError:
raise ValueError("input string can not be transform")
else:
return _result
return wrapper
@TypeDecorators.to_int
def do_nothing(string: str):
return string
print(do_nothing('25'))
print(type(do_nothing('25')))
@TypeDecorators.to_bool
def do_nothing(string: str):
return string
print(do_nothing('1'))
print(type(do_nothing('0')))
@TypeDecorators.to_float
def do_nothing(string: str):
return string
print(do_nothing('1.2'))
print(type(do_nothing('0')))
@TypeDecorators.to_str
def do_nothing(string: str):
return string
print(do_nothing('фф'))
print(type(do_nothing('aa')))