teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

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

2021/09/06 00:52

投稿

lehshell
lehshell

スコア1180

answer CHANGED
@@ -17,4 +17,95 @@
17
17
  そのため " local variable 'max_depth' referenced before assignment " のエラーが出ます。
18
18
  helper 関数内で max_depth に代入せず単に max_depth を参照するだけであれば外側のスコープにある maxDepth 関数の max_depth にアクセスできます。
19
19
 
20
- 対して self.max_depth の場合は helper 関数内で self.max_depth に代入しようがしまいが maxDepth 関数の引数の self の max_depth にアクセスします。
20
+ 対して self.max_depth の場合は helper 関数内で self.max_depth に代入しようがしまいが maxDepth 関数の引数の self の max_depth にアクセスします。
21
+
22
+ **追加質問の回答**
23
+
24
+ > ただ、self.max_depth=0 は、maxDepth関数内で宣言されています。
25
+ > グローバル変数は、関数外でイニシャライズするものとばかり思っていたのですが、
26
+ > 上記のような形で、グローバル変数をイニシャライズすることも多いのでしょうか。
27
+
28
+ self.max_depth はグローバル変数ではありません。
29
+ self.max_depth=0 は 元々 self.max_depth が定義されていなければここで self のインスタンス変数を定義しています。
30
+
31
+ ```Python
32
+ def __init__(self):
33
+ self.max_depth = 0
34
+ ```
35
+
36
+ ```Python
37
+ def maxDepth(self, root: Optional[TreeNode]) -> int:
38
+ self.max_depth = 0
39
+ ```
40
+ の違いの例を示します。引数を少なくした例にしています。
41
+
42
+ まず ```__init__``` と ```maxDepth``` が単なる関数の場合
43
+
44
+ ```Python
45
+ def __init__(self):
46
+ self.max_depth = 0
47
+
48
+ def maxDepth(self):
49
+ print(self.max_depth)
50
+
51
+ class Goo:
52
+ pass
53
+
54
+ g = Goo()
55
+ __init__(g)
56
+ maxDepth(g)
57
+ g2 = Goo()
58
+ maxDepth(g2) # AttributeError: 'Goo' object has no attribute 'max_depth'
59
+ ```
60
+
61
+ そして ```__init__``` と ```maxDepth``` がクラス内のメソッドの場合(本来質問時に明示すべきです)
62
+
63
+ ```Python
64
+ class Foo:
65
+ def __init__(self):
66
+ self.max_depth = 0
67
+
68
+ def maxDepth(self):
69
+ print(self.max_depth)
70
+
71
+ f = Foo()
72
+ f.maxDepth()
73
+ ```
74
+
75
+ は問題なく
76
+
77
+ ```Python
78
+ class Foo:
79
+ def __init__(self):
80
+ pass
81
+
82
+ def maxDepth(self):
83
+ self.max_depth = 0
84
+ print(self.max_depth)
85
+
86
+ def minDepth(self):
87
+ print(self.max_depth)
88
+
89
+ f = Foo()
90
+ f.maxDepth()
91
+ f.minDepth()
92
+
93
+ ```
94
+ も問題ないように見えますが、実際は
95
+
96
+ ```Python
97
+ class Foo:
98
+ def __init__(self):
99
+ pass
100
+
101
+ def maxDepth(self):
102
+ self.max_depth = 0
103
+ print(self.max_depth)
104
+
105
+ def minDepth(self):
106
+ print(self.max_depth)
107
+
108
+ f = Foo()
109
+ f.minDepth() # AttributeError: 'Foo' object has no attribute 'max_depth'
110
+ ```
111
+ と maxDepth を呼び出さずに minDepth を呼び出すと問題になります。