回答編集履歴
3
追記
test
CHANGED
@@ -28,6 +28,108 @@
|
|
28
28
|
|
29
29
|
#3 2 1
|
30
30
|
|
31
|
+
```
|
31
32
|
|
32
33
|
|
34
|
+
|
35
|
+
特定の名前の付いた関数だけ配列として使いたい場合
|
36
|
+
|
37
|
+
--
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
my_func.py
|
42
|
+
|
43
|
+
```Python
|
44
|
+
|
45
|
+
#変数の2倍
|
46
|
+
|
47
|
+
def mf_multi(x):
|
48
|
+
|
49
|
+
y = x * 2
|
50
|
+
|
51
|
+
return y
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
#変数の1/2
|
56
|
+
|
57
|
+
def mf_div(x):
|
58
|
+
|
59
|
+
y = x / 2
|
60
|
+
|
61
|
+
return y
|
62
|
+
|
63
|
+
|
64
|
+
|
65
|
+
def mf_sum(x):
|
66
|
+
|
67
|
+
y = x + 2
|
68
|
+
|
69
|
+
return y
|
70
|
+
|
71
|
+
|
72
|
+
|
73
|
+
def mf_dif(x):
|
74
|
+
|
75
|
+
y = x - 1
|
76
|
+
|
77
|
+
return y
|
78
|
+
|
79
|
+
|
80
|
+
|
81
|
+
# これは含まれない
|
82
|
+
|
83
|
+
def other_func(x):
|
84
|
+
|
85
|
+
pass
|
86
|
+
|
87
|
+
|
88
|
+
|
89
|
+
# mf_~という名前のついた関数のリストを返す
|
90
|
+
|
91
|
+
def get_func():
|
92
|
+
|
93
|
+
func = []
|
94
|
+
|
95
|
+
for k,v in globals().items():
|
96
|
+
|
97
|
+
if k.startswith('mf_'):
|
98
|
+
|
99
|
+
func.append(v)
|
100
|
+
|
101
|
+
return func
|
102
|
+
|
33
103
|
```
|
104
|
+
|
105
|
+
|
106
|
+
|
107
|
+
main.py
|
108
|
+
|
109
|
+
```Python
|
110
|
+
|
111
|
+
import my_func
|
112
|
+
|
113
|
+
|
114
|
+
|
115
|
+
num = [8, 4, 6, 2]
|
116
|
+
|
117
|
+
func = my_func.get_func()
|
118
|
+
|
119
|
+
print(func) # [<function mf_multi at 0x0000020C173DFE58>, <function mf_div at 0x0000020C17426558>, <function mf_sum at 0x0000020C17426798>, <function mf_dif at 0x0000020C17426A68>]
|
120
|
+
|
121
|
+
|
122
|
+
|
123
|
+
for i, n in enumerate(num):
|
124
|
+
|
125
|
+
print(i, n, func[i](n))
|
126
|
+
|
127
|
+
#0 8 16
|
128
|
+
|
129
|
+
#1 4 2.0
|
130
|
+
|
131
|
+
#2 6 8
|
132
|
+
|
133
|
+
#3 2 1
|
134
|
+
|
135
|
+
```
|
2
追記
test
CHANGED
@@ -9,6 +9,10 @@
|
|
9
9
|
num = [8, 4, 6, 2]
|
10
10
|
|
11
11
|
func = [my_func.multi, my_func.div, my_func.sum, my_func.dif]
|
12
|
+
|
13
|
+
|
14
|
+
|
15
|
+
print(type(my_func.multi)) # <class 'function'>
|
12
16
|
|
13
17
|
|
14
18
|
|
1
修正
test
CHANGED
@@ -2,45 +2,13 @@
|
|
2
2
|
|
3
3
|
```Python
|
4
4
|
|
5
|
-
#変数の2倍
|
6
|
-
|
7
|
-
def multi(x):
|
8
|
-
|
9
|
-
y = x * 2
|
10
|
-
|
11
|
-
|
5
|
+
import my_func
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
#変数の1/2
|
16
|
-
|
17
|
-
def div(x):
|
18
|
-
|
19
|
-
y = x / 2
|
20
|
-
|
21
|
-
return y
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
def sum(x):
|
26
|
-
|
27
|
-
y = x + 2
|
28
|
-
|
29
|
-
return y
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
def dif(x):
|
34
|
-
|
35
|
-
y = x - 1
|
36
|
-
|
37
|
-
return y
|
38
6
|
|
39
7
|
|
40
8
|
|
41
9
|
num = [8, 4, 6, 2]
|
42
10
|
|
43
|
-
func = [multi, div, sum, dif]
|
11
|
+
func = [my_func.multi, my_func.div, my_func.sum, my_func.dif]
|
44
12
|
|
45
13
|
|
46
14
|
|
@@ -56,4 +24,6 @@
|
|
56
24
|
|
57
25
|
#3 2 1
|
58
26
|
|
27
|
+
|
28
|
+
|
59
29
|
```
|