回答編集履歴
1
decoratorについて
test
CHANGED
@@ -35,3 +35,89 @@
|
|
35
35
|
# --end--
|
36
36
|
|
37
37
|
```
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
----
|
42
|
+
|
43
|
+
@wrapsなしだと何をwrapしたのか分からなくなってしまう問題があります。
|
44
|
+
|
45
|
+
|
46
|
+
|
47
|
+
```Python
|
48
|
+
|
49
|
+
def deco(func):
|
50
|
+
|
51
|
+
def wrapper(*args, **kwargs):
|
52
|
+
|
53
|
+
print('--start--')
|
54
|
+
|
55
|
+
func(*args, **kwargs)
|
56
|
+
|
57
|
+
print('--end--')
|
58
|
+
|
59
|
+
return wrapper
|
60
|
+
|
61
|
+
|
62
|
+
|
63
|
+
@deco
|
64
|
+
|
65
|
+
def test(name):
|
66
|
+
|
67
|
+
"""How to use"""
|
68
|
+
|
69
|
+
print(f'Hello Decorator - {name}')
|
70
|
+
|
71
|
+
|
72
|
+
|
73
|
+
print(test.__doc__)
|
74
|
+
|
75
|
+
# None
|
76
|
+
|
77
|
+
print(test)
|
78
|
+
|
79
|
+
# <function deco.<locals>.wrapper at 0x102dc38c8>
|
80
|
+
|
81
|
+
```
|
82
|
+
|
83
|
+
|
84
|
+
|
85
|
+
@wrapsを使うと、もとのオブジェクトの属性を引き継ぐことができます。
|
86
|
+
|
87
|
+
```Python
|
88
|
+
|
89
|
+
def deco(func):
|
90
|
+
|
91
|
+
@wraps
|
92
|
+
|
93
|
+
def wrapper(*args, **kwargs):
|
94
|
+
|
95
|
+
print('--start--')
|
96
|
+
|
97
|
+
func(*args, **kwargs)
|
98
|
+
|
99
|
+
print('--end--')
|
100
|
+
|
101
|
+
return wrapper
|
102
|
+
|
103
|
+
|
104
|
+
|
105
|
+
@deco
|
106
|
+
|
107
|
+
def test(name):
|
108
|
+
|
109
|
+
"""How to use"""
|
110
|
+
|
111
|
+
print(f'Hello Decorator - {name}')
|
112
|
+
|
113
|
+
|
114
|
+
|
115
|
+
print(test.__doc__)
|
116
|
+
|
117
|
+
# How to use
|
118
|
+
|
119
|
+
print(test)
|
120
|
+
|
121
|
+
# <function test at 0x102e98488>
|
122
|
+
|
123
|
+
```
|