回答編集履歴

1

追加質問に対する回答追記

2021/09/06 00:52

投稿

lehshell
lehshell

スコア1147

test CHANGED
@@ -37,3 +37,185 @@
37
37
 
38
38
 
39
39
  対して self.max_depth の場合は helper 関数内で self.max_depth に代入しようがしまいが maxDepth 関数の引数の self の max_depth にアクセスします。
40
+
41
+
42
+
43
+ **追加質問の回答**
44
+
45
+
46
+
47
+ > ただ、self.max_depth=0 は、maxDepth関数内で宣言されています。
48
+
49
+ > グローバル変数は、関数外でイニシャライズするものとばかり思っていたのですが、
50
+
51
+ > 上記のような形で、グローバル変数をイニシャライズすることも多いのでしょうか。
52
+
53
+
54
+
55
+ self.max_depth はグローバル変数ではありません。
56
+
57
+ self.max_depth=0 は 元々 self.max_depth が定義されていなければここで self のインスタンス変数を定義しています。
58
+
59
+
60
+
61
+ ```Python
62
+
63
+ def __init__(self):
64
+
65
+ self.max_depth = 0
66
+
67
+ ```
68
+
69
+
70
+
71
+ ```Python
72
+
73
+ def maxDepth(self, root: Optional[TreeNode]) -> int:
74
+
75
+ self.max_depth = 0
76
+
77
+ ```
78
+
79
+ の違いの例を示します。引数を少なくした例にしています。
80
+
81
+
82
+
83
+ まず ```__init__``` と ```maxDepth``` が単なる関数の場合
84
+
85
+
86
+
87
+ ```Python
88
+
89
+ def __init__(self):
90
+
91
+ self.max_depth = 0
92
+
93
+
94
+
95
+ def maxDepth(self):
96
+
97
+ print(self.max_depth)
98
+
99
+
100
+
101
+ class Goo:
102
+
103
+ pass
104
+
105
+
106
+
107
+ g = Goo()
108
+
109
+ __init__(g)
110
+
111
+ maxDepth(g)
112
+
113
+ g2 = Goo()
114
+
115
+ maxDepth(g2) # AttributeError: 'Goo' object has no attribute 'max_depth'
116
+
117
+ ```
118
+
119
+
120
+
121
+ そして ```__init__``` と ```maxDepth``` がクラス内のメソッドの場合(本来質問時に明示すべきです)
122
+
123
+
124
+
125
+ ```Python
126
+
127
+ class Foo:
128
+
129
+ def __init__(self):
130
+
131
+ self.max_depth = 0
132
+
133
+
134
+
135
+ def maxDepth(self):
136
+
137
+ print(self.max_depth)
138
+
139
+
140
+
141
+ f = Foo()
142
+
143
+ f.maxDepth()
144
+
145
+ ```
146
+
147
+
148
+
149
+ は問題なく
150
+
151
+
152
+
153
+ ```Python
154
+
155
+ class Foo:
156
+
157
+ def __init__(self):
158
+
159
+ pass
160
+
161
+
162
+
163
+ def maxDepth(self):
164
+
165
+ self.max_depth = 0
166
+
167
+ print(self.max_depth)
168
+
169
+
170
+
171
+ def minDepth(self):
172
+
173
+ print(self.max_depth)
174
+
175
+
176
+
177
+ f = Foo()
178
+
179
+ f.maxDepth()
180
+
181
+ f.minDepth()
182
+
183
+
184
+
185
+ ```
186
+
187
+ も問題ないように見えますが、実際は
188
+
189
+
190
+
191
+ ```Python
192
+
193
+ class Foo:
194
+
195
+ def __init__(self):
196
+
197
+ pass
198
+
199
+
200
+
201
+ def maxDepth(self):
202
+
203
+ self.max_depth = 0
204
+
205
+ print(self.max_depth)
206
+
207
+
208
+
209
+ def minDepth(self):
210
+
211
+ print(self.max_depth)
212
+
213
+
214
+
215
+ f = Foo()
216
+
217
+ f.minDepth() # AttributeError: 'Foo' object has no attribute 'max_depth'
218
+
219
+ ```
220
+
221
+ と maxDepth を呼び出さずに minDepth を呼び出すと問題になります。