<?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>「キーワード引数」タグの記事一覧Python Tech</title>
	<atom:link href="https://tech.nkhn37.net/tag/keyword-arguments-jpn/feed/" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Sun, 26 Oct 2025 05:58:19 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://tech.nkhn37.net/wp-content/uploads/2021/01/cropped-lion-normal-clear-1-32x32.png</url>
	<title>「キーワード引数」タグの記事一覧Python Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】関数定義の基本</title>
		<link>https://tech.nkhn37.net/python-function-basic/</link>
					<comments>https://tech.nkhn37.net/python-function-basic/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Sun, 31 Jan 2021 00:00:00 +0000</pubDate>
				<category><![CDATA[関数]]></category>
		<category><![CDATA[**kwargs]]></category>
		<category><![CDATA[*args]]></category>
		<category><![CDATA[キーワード引数]]></category>
		<category><![CDATA[デフォルト引数]]></category>
		<category><![CDATA[位置引数]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=572</guid>

					<description><![CDATA[Pythonで関数を定義する方法について解説します。関数定義では、色々な引数の種類や使い方が登場します。それらの使い方を含めて詳細を説明していきます。 Pythonにおける関数 関数とは、特定の処理を実行するためのコード [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Pythonで<span class="marker"><strong>関数を定義する方法</strong></span>について解説します。関数定義では、色々な引数の種類や使い方が登場します。それらの使い方を含めて詳細を説明していきます。</p>



<h2 class="wp-block-heading jinr-heading d--bold" id="関数の定義方法">Pythonにおける関数</h2>



<p class="wp-block-paragraph"><span class="marker"><strong>関数</strong></span>とは、特定の処理を実行するためのコードのまとまりのことです。適切な関数定義を行うことで、再利用可能なコードブロックとして様々な場所から必要な時に呼び出して処理を実行することができるようになります。</p>



<p class="wp-block-paragraph">この記事では、Pythonにおける<span class="marker"><strong>関数定義の基本</strong></span>を紹介します。また、関数では引数の扱いが重要です。様々な引数の種類や使い方についても詳細に説明します。</p>



<h3 class="wp-block-heading jinr-heading d--bold" id="基本的な関数宣言方法">基本的な関数宣言</h3>



<p class="wp-block-paragraph">関数は、<span class="marker"><strong><code>def</code></strong></span>を使って以下のように定義します。<code>def</code> は「定義する」の意味の define を意味する略となっています。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 関数定義の基本
def print_hello_world():
    print("hello world!")


if __name__ == "__main__":
    print_hello_world()</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
hello world!</pre>



<p class="wp-block-paragraph">上記例では、<code>"hello world!"</code>と表示する関数<code>print_hello_world</code>を定義しています。関数を呼び出す際には、<code>print_hello_world()</code>というように呼び出すことが可能です。</p>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox5 ">
			<i class="jif jin-ifont-v2speaker" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph"><strong><code>if __name__ == "__main__":</code> の意味について</strong></p>



<p class="wp-block-paragraph">この構文は、Python のエントリーポイントを示すために使用されます。具体的にはスクリプトが直接実行された場合と、他モジュールからインポートされた場合で挙動が異なります。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>状況</th><th>動作概要</th></tr></thead><tbody><tr><td>スクリプトが直接実行されたとき</td><td><code>__name__</code>  が <code>__main__</code> となるため、<code>if</code> ブロック内のコードが実行されます。</td></tr><tr><td>他モジュールからインポートされたとき</td><td><code>__name__</code> はモジュール名となるため、<code>if</code> ブロック内のコードは実行されません。</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><code>if __name__ == "__main__":</code> ブロックがない場合、スクリプトをインポートするたびにスクリプト内のコードが上から順に実行されます。このような動きは、ライブラリとして使う場合には意図しない不具合の原因となります。この if ブロックにより、インポートの際の不必要なコード実行を防ぐことができます。</p>



<p class="wp-block-paragraph">Python でのベストプラクティスの書き方の1つです。</p>
</div>
		</div></section>



<h3 class="wp-block-heading jinr-heading d--bold" id="関数の引数と返り値の宣言方法">関数の引数と返り値の宣言</h3>



<p class="wp-block-paragraph">関数は、引数を受け取り処理を実行し、結果を返り値として呼び出し元へ返却します。引数は関数の<code>()</code>内に記載をし、返り値については<code>return</code>を使用して返却します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 関数定義 引数、返却値
def func_2(num):
    return 2 * num


if __name__ == "__main__":
    x1 = 5
    y1 = func_2(x1)
    print(f"x1 = {x1}, y1 = {y1}")

    x2 = 10
    y2 = func_2(x2)
    print(f"x2 = {x2}, y2 = {y2}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
x1 = 5, y1 = 10
x2 = 10, y2 = 20</pre>



<p class="wp-block-paragraph">上記例の<code>func_2</code>関数は受け取った数値を2倍にして返却する関数です。</p>



<p class="wp-block-paragraph">関数定義の<code>()</code>内に引数となる変数を列挙すると関数内で使用することができます。関数定義での引数は<span class="marker"><strong>仮引数</strong></span>と呼ばれ、呼び出し時に渡される引数は<span class="marker"><strong>実引数</strong></span>と呼ばれます。</p>



<p class="wp-block-paragraph">返却値を呼び出し元に返す場合には、<span class="marker"><strong><code>return</code></strong></span>を使用します。変数を指定するか、式を直接指定した場合は式が評価された結果が返却されます。返り値がない場合は、<code>return</code>を省略した関数とするか、<code>return None</code>を用いることが一般的です。</p>



<p class="wp-block-paragraph">関数の呼び出し時には、<code>y1 = func_2(x1)</code>のように呼び出しができます。実引数<code>x1</code>の値が関数の仮引数<code>num</code>に渡され処理が実行されます。もちろん<code>def func_values(x1, x2):</code>のように複数の引数を受け取る関数を定義することも可能です。</p>



<p class="wp-block-paragraph">関数の基本的な部分は以上となります。関数の引数にはいくつかの種類があるため、以降では、関数の引数の種類と使い方についてより詳細に説明します。</p>



<h2 class="wp-block-heading jinr-heading d--bold" id="関数の引数の種類と使い方">関数の引数の種類と使い方</h2>



<p class="wp-block-paragraph">関数の引数にはいくつかの種類や考え方があります。以降では「位置引数」「キーワード引数」「引数のデフォルト値」「<code>*args</code>」「<code>**kwargs</code>」といったトピックスについて詳細を説明していきます。</p>



<h3 class="wp-block-heading jinr-heading d--bold" id="位置引数">位置引数</h3>



<p class="wp-block-paragraph"><span class="marker"><strong>位置引数（positional arguments）</strong></span>とは、関数を呼び出す際に引数の順番に基づいて値を渡す方法です。位置引数では、関数定義時に指定されている引数の順番に値を渡す必要があります。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def make_profile(first, last, birth):
    return {"first name": first, "last name": last, "birthday": birth}


if __name__ == "__main__":
    first_name = "Taro"
    last_name = "Python"
    birthday = "2021/1/1"

    # 位置引数にて指定
    profile = make_profile(first_name, last_name, birthday)
    print(profile)

    profile = make_profile(last_name, first_name, birthday)
    print(profile)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
{'first name': 'Taro', 'last name': 'Python', 'birthday': '2021/1/1'}
{'first name': 'Python', 'last name': 'Taro', 'birthday': '2021/1/1'}</pre>



<p class="wp-block-paragraph">上記例は、入力された名前(<code>first_name</code>)、苗字(<code>last_name</code>)、誕生日(<code>birthday</code>)を受け取って辞書にして返却する<code>make_profile</code>関数です。</p>



<p class="wp-block-paragraph">位置引数を使用する場合には、引数の位置と順番が非常に重要です。例えば、上記例で2回目に呼び出した際には、<code>fist_name</code>と<code>last_name</code>の変数の指定位置が入れ替わっています。結果として、名前である<code>Taro</code>が苗字として処理されてしまっています。</p>



<p class="wp-block-paragraph">位置引数では、呼び出し時の順序が重要です。呼び出し順序を間違えると予期しない動作をする可能性がありますので十分に注意しましょう。</p>



<h3 class="wp-block-heading jinr-heading d--bold" id="キーワード引数">キーワード引数</h3>



<p class="wp-block-paragraph"><span class="marker"><strong>キーワード引数（keyword arguments）</strong></span>とは、関数を呼び出す際に引数名を指定して値を渡す方法です。関数定義で指定された引数名に基づいて値を渡すため、順番に依存せずに引数を指定できることが特徴です。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def make_profile(first, last, birth):
    return {"first name": first, "last name": last, "birthday": birth}


if __name__ == "__main__":
    first_name = "Taro"
    last_name = "Python"
    birthday = "2021/1/1"

    # キーワード引数にて指定
    profile = make_profile(birth=birthday, last=last_name, first=first_name)
    print(profile)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
{'first name': 'Taro', 'last name': 'Python', 'birthday': '2021/1/1'}</pre>



<p class="wp-block-paragraph">上記例は、位置引数の説明時と同様の関数です。キーワード引数の呼び出しでは、「<code>仮引数名=</code>」という形で指定します。</p>



<p class="wp-block-paragraph">キーワード引数では呼び出し時に仮引数名を指定するため順番は関係がなくなります。上記例でいうと、<code>make_profile(birth=birthday, last=last_name, first=first_name)</code>のように関数定義時の順序とは異なる順序で指定しているにも関わらず、結果は正しくなっていることが分かります。</p>



<h3 class="wp-block-heading jinr-heading d--bold" id="デフォルト引数値の指定方法">引数のデフォルト値</h3>



<p class="wp-block-paragraph">関数は、引数として定義したものを呼び出し元で全て設定しないとエラーとなってしまいます。ただし、<span class="marker"><strong>引数のデフォルト値</strong></span>を定義しておくことで、呼び出し元で引数の指定がなかった場合に、デフォルト値を代わりに設定して関数を実行することができます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># デフォルト値を指定
def make_profile(first=None, last=None, birth=None):
    return {"first name": first, "last name": last, "birthday": birth}


if __name__ == "__main__":
    first_name = "Taro"
    last_name = "Python"
    birthday = "2021/1/1"

    # キーワード引数にて指定
    profile = make_profile(first=first_name, birth=birthday)
    print(profile)

    profile = make_profile(first=first_name, last=last_name, birth=birthday)
    print(profile)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
{'first name': 'Taro', 'last name': None, 'birthday': '2021/1/1'}
{'first name': 'Taro', 'last name': 'Python', 'birthday': '2021/1/1'}</pre>



<p class="wp-block-paragraph">引数のデフォルト値は「<code>仮引数=デフォルト値</code>」という形で定義します。呼び出し元で引数が指定された場合は、その値が使用されますが、指定がない場合はデフォルト値が使用されます。</p>



<p class="wp-block-paragraph">なお、デフォルト値を設定する引数は、<span class="marker"><strong>デフォルト値が設定されていない引数の後</strong></span>に定義する必要があるので注意してください。例えば、<code>def make_profile(first=None, last, birth):</code>といった定義はエラーとなります。</p>



<h3 class="wp-block-heading jinr-heading d--bold" id="argsによる位置引数のタプル受取"><code>*args</code> による任意個の位置引数の受け取り</h3>



<p class="wp-block-paragraph">関数の引数として任意の個数の引数を渡したい場合には、関数の引数として<span class="marker"><strong><code>*args</code></strong></span>を定義します。なお、<code>args</code>という名称の使用は必須ではありませんが、Pythonを使っている人は通例としてargumentsを意味する<code>args</code>という名称を使用します。</p>



<h4 class="wp-block-heading jinr-heading d--bold">基本的な使い方</h4>



<p class="wp-block-paragraph"><code>*args</code>による引数の受け取りは以下のようにします。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># *argsによる位置引数の受け取り
def print_input(*args):
    print(type(args))
    for i, arg in enumerate(args):
        print(f"arg[{i}] = {arg}")


if __name__ == "__main__":
    print_input(1, 2, "A", "B", [1, 2])</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
&lt;class 'tuple'>
arg[0] = 1
arg[1] = 2
arg[2] = A
arg[3] = B
arg[4] = [1, 2]</pre>



<p class="wp-block-paragraph"><code>*args</code>として引数を設定した場合には、受け取った引数はタプルとなります。上記例では、<code>print_input(1, 2, "A", "B", [1, 2])</code>のように合計5つの引数を受け取ることができています。</p>



<h4 class="wp-block-heading jinr-heading d--bold">通常の引数との組み合わせ</h4>



<p class="wp-block-paragraph"><code>＊args</code>は、以下のように通常の引数と組み合わせて使用することができます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def print_input(input1, input2, *args):
    print(input1)
    print(input2)
    for i, arg in enumerate(args):
        print(f'arg[{i}] = {arg}')


if __name__ == '__main__':
    print_input(1, 2, 'A', 'B', 'C')</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
1
2
arg[0] = A
arg[1] = B
arg[2] = C</pre>



<p class="wp-block-paragraph">上記例では、<code>input1</code>、<code>input2</code>は位置引数として指定された順で値が設定され、残りの引数がすべて<code>args</code>にまとめられていることが分かります。これにより、関数として重要な引数は、位置引数として定義しておき、任意の引数を<code>args</code>にまとめてしまうといったことができます。</p>



<p class="wp-block-paragraph">なお、<span class="marker"><strong>通常の引数は*argsの前に定義する必要がある</strong></span>ため注意してください。</p>



<h3 class="wp-block-heading jinr-heading d--bold" id="kwargsによるキーワード引数の辞書受取"><code>**kwargs</code> による任意個のキーワード引数の受け取り</h3>



<p class="wp-block-paragraph">関数の引数として任意の個数のキーワード引数を渡したい場合には、関数の引数として<span class="marker"><strong><code>**kwargs</code></strong></span>を定義します。なお、<code>kwargs</code>という名称は必須ではありませんが、Pythonを使っている人は通例としてkeyword argumentsを意味する<code>kwargs</code>という名称を使用します。</p>



<h4 class="wp-block-heading jinr-heading d--bold">基本的な使い方</h4>



<p class="wp-block-paragraph"><code>**kwargs</code>によるキーワード引数の受け取りは以下のようにします。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># **kwargsによるキーワード引数の辞書受取
def print_input(**kwargs):
    print(type(kwargs))
    for k, v in kwargs.items():
        print(f"key: {k}, value:{v}")


if __name__ == "__main__":
    print_input(opt1=1, opt2=2, value="python")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
&lt;class 'dict'>
key: opt1, value:1
key: opt2, value:2
key: value, value:python</pre>



<p class="wp-block-paragraph"><code>**kwargs</code>として引数を指定した場合には、受け取った引数は辞書となります。上記例では、合計3つのキーワード引数を受け取ることができています。<code>**kwargs</code>の使用は、特に複数のオプションとなる引数を関数に渡す場合などに非常に便利です。</p>



<h4 class="wp-block-heading jinr-heading d--bold">通常の引数や <code>*args</code> との組み合わせ</h4>



<p class="wp-block-paragraph"><code>**kwargs</code>は、以下のように通常の引数や<code>*args</code>と組み合わせて使用することができます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 通常の位置引数や*argsとの組み合わせ
def print_input(in1, in2, *args, **kwargs):
    print(in1)
    print(in2)
    for i, arg in enumerate(args):
        print(f"arg[{i}] = {arg}")

    for k, v in kwargs.items():
        print(f"key: {k}, value:{v}")


if __name__ == "__main__":
    print_input(1, 2, "A", "B", "C", opt1=1, opt2=2, name="python")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
1
2
arg[0] = A
arg[1] = B
arg[2] = C
key: opt1, value:1
key: opt2, value:2
key: name, value:python</pre>



<p class="wp-block-paragraph">上記の例では、通常の位置引数である<code>in1</code>, <code>in2</code>、任意個の引数の<code>*args</code>、任意個のキーワード引数の<code>**kwargs</code>を<code>print_input</code>関数の引数にしています。このように組み合わせをすることで、非常に柔軟に関数の挙動を定義することが可能になってきます。</p>



<p class="wp-block-paragraph">ただし、引数の順は、<span class="marker"><strong>通常の引数、<code>*args</code>、<code>**kwargs</code>の順で定義する必要がある</strong></span>ため注意してください。</p>



<h3 class="wp-block-heading jinr-heading d--bold" id="関数のデフォルト引数に関する注意事項">関数の引数に関する注意事項</h3>



<p class="wp-block-paragraph">ここでは関数の引数に関する注意事項を説明します。</p>



<h4 class="wp-block-heading jinr-heading d--bold">デフォルト値にはミュータブルな型を使うべきではない</h4>



<p class="wp-block-paragraph">関数の引数の<span class="marker"><strong>デフォルト値にはミュータブル（mutable）な値を使うべきではありません</strong></span>。</p>



<p class="wp-block-paragraph">デフォルト値にミュータブルな型を使用すると、同じインスタンスが再利用されてしまい、意図しない動作を引き起こすことがあります。以下の例で見てみましょう。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def sample_function(in1, tmp_list=[]):
    tmp_list.append(in1)
    return tmp_list


if __name__ == '__main__':
    result1 = sample_function('A')
    print(result1)

    result2 = sample_function('B')
    print(result2)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
['A']
['A', 'B']</pre>



<p class="wp-block-paragraph">上記例のsample_function関数は、値とリストを受け取ってリストに値を追加する関数です。デフォルト値として空リスト<code>[]</code>を設定しています。この時、前提としてプログラムを書いた人はリストが指定されていないときは新しくリストを作成することを想定しているとします。</p>



<p class="wp-block-paragraph">関数の呼び出し結果を見てみましょう。2回呼び出しを行っており、いずれも<code>tmp_list</code>に渡すリストは指定していません。そのため、結果は1回目は<code>['A']</code>、2回目は<code>['B']</code>となってほしいわけです。しかし、2回目の呼び出しでは結果が<code>['A', 'B']</code>となってしまいました。</p>



<p class="wp-block-paragraph">このような結果となるのは、Pythonでは<span class="marker"><strong>関数のデフォルト値は最初に1回だけ評価される</strong></span>ためです。2回目以降の呼び出しでは既に<code>'A'</code>が追加されているリストを使ってしまうため、<code>['A', 'B']</code>となりました。</p>



<p class="wp-block-paragraph">このように、ミュータブルな型をデフォルト値に使ってしまうと想定外の挙動をしてしまうため注意してください。</p>



<p class="wp-block-paragraph">このように想定外の挙動をする可能性があるため、<span class="marker"><strong>ミュータブルな型をデフォルト値に使用することは避ける</strong></span>ようにしてください。</p>



<h4 class="wp-block-heading jinr-heading d--bold">ミュータブルなデフォルト値を使いたい場合</h4>



<p class="wp-block-paragraph">上記では、ミュータブルな値を使うべきではないということで例を紹介しましたが、では実際にどのような解決策があるでしょうか。</p>



<p class="wp-block-paragraph">このような場合は、以下のようにデフォルト値として<code>None</code>を指定して起き、関数内で<code>None</code>であった場合に初期化する方法が適切です。この方法では、毎回新しいリストが作成されるため安全です。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def sample_function(in1, tmp_list=None):
    if tmp_list is None:
        tmp_list = []
    tmp_list.append(in1)
    return tmp_list


if __name__ == '__main__':
    result1 = sample_function('A')
    print(result1)

    result2 = sample_function('B')
    print(result2)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
['A']
['B']</pre>



<p class="wp-block-paragraph">上記結果では、想定した通り結果では、呼び出しの1回目は<code>['A']</code>、2回目は<code>['B']</code>という結果となりました。</p>



<h2 class="wp-block-heading jinr-heading d--bold">まとめ</h2>



<p class="wp-block-paragraph">Python で<span class="marker"><strong>関数を定義する方法</strong></span>について解説しました。また、関数定義では、色々な引数の種類や使い方について紹介しています。</p>



<p class="wp-block-paragraph">関数の定義では <code>def</code> を使って、必要に応じて引数や返り値を設定して定義します。</p>



<p class="wp-block-paragraph">引数では、位置引数、キーワード引数といった考え方があり、<code>*args</code> や <code>**kwargs</code> といった任意個の引数を渡す仕組みがあります。引数が渡されない時のデフォルト引数を設定することができますが、リスト、辞書などのミュータブルな型を設定するとバグにつながりやすいため注意しましょう。</p>



<p class="wp-block-paragraph">関数の定義は、プログラミングでも重要なので基本をしっかり押さえましょう。パッケージなどを使う際にどのように呼び出すことができるかを調べる際にも関数定義の構造をしっかり理解しておくことが役に立ちます。</p>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--heading-box8  "><div class="a--simple-box-title d--bold">ソースコード</div><div class="c--simple-box-inner">
<p class="wp-block-paragraph">上記で紹介しているソースコードについては <a href="https://github.com/nkhn37/python-tech-sample-source/tree/main/python-basic/function/basics" target="_blank" rel="noreferrer noopener">GitHub</a> にて公開しています。参考にしていただければと思います。</p>
</div></div></section>


<section class="b--jinr-block b--jinr-blogcard d--blogcard-hover-up d--blogcard-style1 d--blogcard-mysite t--round "><div class="a--blogcard-label ef">あわせて読みたい</div><a class="o--blogcard-link t--round" href="https://tech.nkhn37.net/python-tech-summary-page/"><div class="c--blogcard-image"><img decoding="async" class="a--blogcard-img-src" width="128" height="72" src="https://tech.nkhn37.net/wp-content/uploads/2024/08/Python-Tech-Pythonプログラミングガイド_new1-640x360.jpg" alt="【Python Tech】プログラミングガイド" /></div><div class="a--blogcard-title d--bold">【Python Tech】プログラミングガイド</div></a></section>]]></content:encoded>
					
					<wfw:commentRss>https://tech.nkhn37.net/python-function-basic/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: tech.nkhn37.net @ 2026-07-04 09:33:03 by W3 Total Cache
-->