<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>__entry__ - プログラミングで遊ブログ</title>
	<atom:link href="https://lemon818.com/tag/__entry__/feed/" rel="self" type="application/rss+xml" />
	<link>https://lemon818.com</link>
	<description>現役システムエンジニアが趣味でプログラミングする自由気ままなブログ</description>
	<lastBuildDate>Mon, 13 Jul 2020 14:19:39 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
<atom:link rel="hub" href="https://pubsubhubbub.appspot.com"/><atom:link rel="hub" href="https://pubsubhubbub.superfeedr.com"/>	<item>
		<title>【Python】with構文とは？知らなくてもいいけど知るとお得な書き方！</title>
		<link>https://lemon818.com/python-with/</link>
		
		<dc:creator><![CDATA[Take]]></dc:creator>
		<pubDate>Mon, 13 Jul 2020 13:34:08 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[with]]></category>
		<category><![CDATA[__entry__]]></category>
		<category><![CDATA[__exit__]]></category>
		<category><![CDATA[構文]]></category>
		<guid isPermaLink="false">https://lemon818.com/?p=4832</guid>

					<description><![CDATA[どーも Takeです。 この記事では、Pythonの「with構文」について簡単に解説します。 &#160; 結論からいいますが、with構文がわからなくてもプログラミング開発はできます。 私は Python を学び始め…]]></description>
										<content:encoded><![CDATA[<p>どーも Takeです。</p>
<p>この記事では、Pythonの「with構文」について簡単に解説します。</p>
<p>&nbsp;</p>
<p>結論からいいますが、<strong>with構文がわからなくても<span style="color: #0000ff;">プログラミング開発はできます</span>。</strong></p>
<p>私は Python を学び始めた当初、<span style="color: #ff0000;"><strong>まったくwith構文がわかりませんでした</strong></span>。</p>
<p>&nbsp;</p>
<p>しかし、知っているとより簡単にソースコードが書くことが可能になり、可読性が向上します。</p>
<p>&nbsp;</p>
<div class="sc_frame_wrap block blue">
<div class="sc_frame_title">with構文を使うことのメリット</div>
<div class="sc_frame ">
<div class="sc_frame_text">
<div class="sc_designlist ol square solid blue">
<ol>
<li>可読性の向上（ソースコードが読みやすくなります！）</li>
<li>安全性の向上（エラー処理なしに処理できます！）</li>
</ol>
</div>
</div>
</div>
</div>
<p>&nbsp;</p>
<p>この記事では with構文とは何なのか？どう使うのか？簡単にまとめます。</p>
<p>&nbsp;</p>
<h2>with構文とは？</h2>
<p>Pythonのwith構文とは、ある処理の開始～終了を「簡単に」「安全に」書くことができる構文です。</p><pre class="crayon-plain-tag">with 開始～終了までの処理</pre><p>
&nbsp;</p>
<p>with構文はファイルのオープン、クローズ処理やデータベースへの接続処理などに使われます。</p>
<p>それでは、つぎに具体的にソースコードを用いて説明します。</p>
<p>&nbsp;</p>
<h2>with構文の具体例</h2>
<p>例として Python で「ファイルの中身を読み込む処理」を「with構文」がある場合、ない場合で説明します。</p>
<p>まずは「with構文なし」の例を下記に示します。</p><pre class="crayon-plain-tag">f = open('test.csv')
print(f.read())
f.close()</pre><p>
&nbsp;</p>
<p>これは「test.csv」ファイルの中身を表示させる処理を行っていますが、</p>
<p>ファイルの中身を表示させるためには</p>
<p>ファイルを開くための「open」関数、ファイルを閉じるための「close」関数を利用する必要があります。</p>
<p>&nbsp;</p>
<p>上記に対し、「with構文あり」の例を下記に示します。</p><pre class="crayon-plain-tag">with open('test.csv') as f:
    s = f.read()

print(s)</pre><p>
&nbsp;</p>
<p>こちらも同様に「test.csv」ファイルの中身を表示させる処理を行っていますが、</p>
<p>上記に比べすっきりかけている（<span style="color: #0000ff;"><strong>可読性が向上している</strong></span>）のではないでしょうか？</p>
<p>&nbsp;</p>
<p>また、こちらでは明示的にファイルを閉じるための処理の記載が<span style="color: #0000ff;"><strong>不要</strong></span>です。</p>
<p>&nbsp;</p>
<p>これら２つのソースコードは同じ3行くらいの短い処理ですが、</p>
<p>仮にこれが100行、200行などの大規模な処理の場合、ファイルの<span style="color: #ff0000;"><strong>クローズ処理を忘れてしまう</strong></span>ケースがあります。</p>
<p>クローズ処理をし忘れたために次の処理が動作し、ファイルアクセスできず後続処理ができなくなる...</p>
<p>そういったリスクを with構文は回避できます。</p>
<p>&nbsp;</p>
<div class="sc_frame_wrap block blue">
<div class="sc_frame_title">with 構文を使うメリット！</div>
<div class="sc_frame ">
<div class="sc_frame_text">
<div class="sc_designlist ol square solid blue">
<ol>
<li>ソースコードがすっきりする！（可読性が向上！）</li>
<li>終了処理を書かなくてよい！（安全性の向上！）</li>
</ol>
</div>
</div>
</div>
</div>
<p>&nbsp;</p>
<h2>with構文で使えるクラスの実装方法</h2>
<p>少し難しい話ですが、Python では自分で作成したクラスをwith構文で利用できます。</p>
<p>クラスを実装する場合、下記２つのメソッドを定義します。</p>
<div class="sc_frame_wrap blue">
<div class="sc_frame ">
<div class="sc_frame_text">
<div class="sc_designlist ol square solid blue">
<ol>
<li>__enter__(self)</li>
<li>__exit__(self, exc_type, exc_val, exc_tb)</li>
</ol>
</div>
</div>
</div>
</div>
<p>&nbsp;</p>
<p>例えば下記のようなソースコードがあるとします。</p><pre class="crayon-plain-tag">class MyClass(object):
        
    def __enter__(self):
        print("enter")
        
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit")

with MyClass() as m:
    print("処理開始！")</pre><p>
&nbsp;</p>
<p>これは「MyClass」クラスを定義し、その中に「__entry__」「__exit__」の２つのメソッドを実装します。</p>
<p>「with MyClass() as m:」でクラスを呼び出すと、下記のようになります。</p><pre class="crayon-plain-tag">enter
処理開始！
exit</pre><p>
&nbsp;</p>
<p>この結果は下記のような流れが動作したためです。</p>
<div class="sc_designlist ol radius solid blue">
<ol>
<li>処理が開始し「__entry__」メソッド処理が実行され、「entry」が表示されます。</li>
<li>with 内の処理が実行され、「処理開始！」が表示されます。</li>
<li>処理が終了し「__exit__」メソッド処理が実行され、「exit」が表示されます。</li>
</ol>
</div>
<p>&nbsp;</p>
<h2>最後に</h2>
<p>いかがでしたでしょうか？</p>
<p>Pythonの「with構文」について簡単に解説しました。</p>
<p>この記事を参考にぜひ「with構文」を使いこなして下さい！</p>
<p>ではでは。</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
