回答編集履歴
5
edit
test
CHANGED
@@ -23,6 +23,18 @@
|
|
23
23
|
|
24
24
|
|
25
25
|
https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
結論は、
|
30
|
+
|
31
|
+
> The best work-around is to just use `__init__` to create an instance variable instead
|
32
|
+
|
33
|
+
|
34
|
+
|
35
|
+
非常に紛らわしいので、どうしてもクラス変数として定義しなければならない場合を除いて、
|
36
|
+
|
37
|
+
インスタンス変数にすべきです。
|
26
38
|
|
27
39
|
|
28
40
|
|
4
edit
test
CHANGED
@@ -31,3 +31,87 @@
|
|
31
31
|
|
32
32
|
|
33
33
|
クラス変数ではなく、グローバルにxが定義してあると、そっちが入ってくるのでますます混乱しそうですね。
|
34
|
+
|
35
|
+
|
36
|
+
|
37
|
+
---
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
追記
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
変数名の探索の際にクラスの名前空間はスキップされます。
|
46
|
+
|
47
|
+
https://www.python.org/dev/peps/pep-0227/
|
48
|
+
|
49
|
+
|
50
|
+
|
51
|
+
```python
|
52
|
+
|
53
|
+
#--- global scope
|
54
|
+
|
55
|
+
x = 1 # x1
|
56
|
+
|
57
|
+
class Dummy:
|
58
|
+
|
59
|
+
#--- class scope
|
60
|
+
|
61
|
+
x = 2 # x2
|
62
|
+
|
63
|
+
y = [x for i in range(3)] #ここのxはx1になります
|
64
|
+
|
65
|
+
|
66
|
+
|
67
|
+
y = [i for i in range(x)] #ここのxはx2になります
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
def y(x): # x3
|
72
|
+
|
73
|
+
#--- function scope
|
74
|
+
|
75
|
+
return x # ここのxはx3になります
|
76
|
+
|
77
|
+
y = y(x)
|
78
|
+
|
79
|
+
|
80
|
+
|
81
|
+
def y(x): # x3
|
82
|
+
|
83
|
+
#--- function scope
|
84
|
+
|
85
|
+
return [x for i in range(3)] # ここのxはx3になります
|
86
|
+
|
87
|
+
y = y(x)
|
88
|
+
|
89
|
+
|
90
|
+
|
91
|
+
def y(dummy):
|
92
|
+
|
93
|
+
#--- function scope
|
94
|
+
|
95
|
+
return x # ここのxはx1になります
|
96
|
+
|
97
|
+
y = y(0)
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
def y(dummy):
|
102
|
+
|
103
|
+
#--- function scope
|
104
|
+
|
105
|
+
return [x for i in range(3)] # ここのxはx1になります
|
106
|
+
|
107
|
+
y = y(0)
|
108
|
+
|
109
|
+
```
|
110
|
+
|
111
|
+
|
112
|
+
|
113
|
+
lambdaは無名関数なのでdefと同じ。
|
114
|
+
|
115
|
+
|
116
|
+
|
117
|
+
グローバルスコープにxが定義していなければ、x1は存在しないので、その部分は未定義エラーになります。
|
3
へんしゅう
test
CHANGED
@@ -23,3 +23,11 @@
|
|
23
23
|
|
24
24
|
|
25
25
|
https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
---
|
30
|
+
|
31
|
+
|
32
|
+
|
33
|
+
クラス変数ではなく、グローバルにxが定義してあると、そっちが入ってくるのでますます混乱しそうですね。
|
2
edit
test
CHANGED
@@ -11,3 +11,15 @@
|
|
11
11
|
|
12
12
|
|
13
13
|
python3.xだと定義されず、python2.xだとエラーなく実行できますね。
|
14
|
+
|
15
|
+
|
16
|
+
|
17
|
+
---
|
18
|
+
|
19
|
+
|
20
|
+
|
21
|
+
Stackoverflowの回答。
|
22
|
+
|
23
|
+
|
24
|
+
|
25
|
+
https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition
|
1
edit
test
CHANGED
@@ -3,3 +3,11 @@
|
|
3
3
|
|
4
4
|
|
5
5
|
リスト内包表記がリークしなくなった結果の気がしますね。
|
6
|
+
|
7
|
+
|
8
|
+
|
9
|
+
---
|
10
|
+
|
11
|
+
|
12
|
+
|
13
|
+
python3.xだと定義されず、python2.xだとエラーなく実行できますね。
|