回答編集履歴
2
実行内容追記
answer
CHANGED
@@ -26,4 +26,16 @@
|
|
26
26
|
with start
|
27
27
|
Hello, world!
|
28
28
|
with end
|
29
|
+
```
|
30
|
+
|
31
|
+
実行内容的には、以下を実行したことになります。
|
32
|
+
with文は、以下の内容を実行するためのシンタックスシュガー(糖衣構文)ということになります。
|
33
|
+
|
34
|
+
```py
|
35
|
+
s = Sample()
|
36
|
+
exit_object = s.__enter__()
|
37
|
+
try:
|
38
|
+
s.hello()
|
39
|
+
finally:
|
40
|
+
exit_object.__exit__()
|
29
41
|
```
|
1
サンプルコード追加
answer
CHANGED
@@ -1,2 +1,29 @@
|
|
1
1
|
`__enter__`メソッドと `__exit__`メソッドを持っているオブジェクトであれば with 文が使えます。
|
2
|
-
参考: https://docs.python.org/ja/3/reference/compound_stmts.html#the-with-statement
|
2
|
+
参考: https://docs.python.org/ja/3/reference/compound_stmts.html#the-with-statement
|
3
|
+
|
4
|
+
サンプルプログラム
|
5
|
+
|
6
|
+
```python
|
7
|
+
class Sample:
|
8
|
+
|
9
|
+
def __enter__(self):
|
10
|
+
print("with start")
|
11
|
+
return self
|
12
|
+
|
13
|
+
def __exit__(self, *args):
|
14
|
+
print("with end")
|
15
|
+
|
16
|
+
def hello(self):
|
17
|
+
print("Hello, world!")
|
18
|
+
|
19
|
+
|
20
|
+
with Sample() as s:
|
21
|
+
s.hello()
|
22
|
+
```
|
23
|
+
|
24
|
+
実行結果:
|
25
|
+
```text
|
26
|
+
with start
|
27
|
+
Hello, world!
|
28
|
+
with end
|
29
|
+
```
|