バックナンバーはこちら。
https://www.simulationroom999.com/blog/compare-matlabpythonscilabjulia-backnumber/
はじめに
前回から、ベクトル、行列から離れて、少しプログラミングより話にシフト。
各ツール、各言語でユーザ関数の作成方法を確認することに。
まずはMATLABについてやったところ。
今回はPython。
登場人物
博識フクロウのフクさん

イラストACにて公開の「kino_k」さんのイラストを使用しています。
https://www.ac-illust.com/main/profile.php?id=iKciwKA9&area=1
エンジニア歴8年の太郎くん

イラストACにて公開の「しのみ」さんのイラストを使用しています。
https://www.ac-illust.com/main/profile.php?id=uCKphAW2&area=1
Pythonの場合

次はPythonかな?

Pythonは対話モードでのユーザ関数定義方法もあるな。
まぁ、スクリプト上の関数定義も本質的にはこれと一緒なんだろうけど。

次はPythonかな?

def 関数名:
のあとに改行。
次の行で半角スペースを1つ以上入れると、損行は巻子内の処理を認識される。
そして、Enter2回で巻子内部処理完了と認識されるな。
こんな感じだ。
>>> def test_func(a,b,c):
... x=a+b
... y=a-c
... return x, y
...
>>>
スクリプトファイルで定義する場合

そして、スクリプトファイル内に記載するもの考え方は一緒だ。
# a,b,cが引数
# x,yが戻り値
def test_func(a,b,c):
x=a+b
y=a-c
return x, y

def 関数名:
のあとに改行。
次の行で半角スペースを1つ以上入れると、損行は巻子内の処理を認識される。
そして、Enter2回で巻子内部処理完了と認識されるな。
こんな感じだ。

関数を呼び出して見る。
>>> [A,B]=test_func(1,2,3)
>>> [A,B]
[3, -2]
他のスクリプトファイルで定義した場合

異なるスクリプトファイルで定義した関数を呼び出す場合は、importを使用する。
上記の関数を”test_func_file.py”に保存したものとした場合、
以下で呼び出せる。
>>> import test_func_file as test
>>> [A,B]=test.test_func(1,2,3)
[3, -2]

import文の行にある”as”ってのは?

異なるスクリプトファイルで定義した関数を呼び出す場合は、importを使用する。
上記の関数を”test_func_file.py”に保存したものとした場合、
以下で呼び出せる。

確かにnpって名前に変えて使ってたね。

あと、当然ではあるのだけど、MATLABと異なり、関数名とファイル名が同一である必要はない。

まぁ、そっちの方が普通ではあるよねー。
まとめ

まとめだよ。
- Pythonの場合のユーザ関数作成方法。
- 対話モードで作成する場合とスクリプトファイル上で作成する場合がある。
- が、実際は対話モード時のルールが共通で適用されてるだけ。
- 他のスクリプトファイルで定義した場合はimportを使用。
- エイリアスで名称変更可能。
- 対話モードで作成する場合とスクリプトファイル上で作成する場合がある。
バックナンバーはこちら。
コメント