関数作成
応用編、まず最初はプログラミング上とっては離せない関数の作成です。
Pythonの関数の最も簡単な例は下記の通りとなります。
# -*- coding: utf-8 -*-
def test_func():
print 'call test_func'
test_func()
--実行結果--
call test_func
「def」で関数を宣言し、インデントによってブロック化された配下の処理を実行します。上記の例では「test_func」が関数の名前で「()」(カッコ)の中に引数を指定します。 関数の最後には必ず「 : 」(コロン)を付けましょう。
先程の関数には引数がありませんでした。今回は引数を設定してみましょう。第一引数と第二引数に数値を、第三引数に四則演算の識別子を指定し、二つの数値を計算させます。
# -*- coding: utf-8 -*-
def test_func(num_1, num_2, oprn):
if oprn == 1:
print u'足し算開始'
print num_1 + num_2
elif oprn == 2:
print u'引き算開始'
print num_1 - num_2
elif oprn == 3:
print u'掛け算開始'
print num_1 * num_2
elif oprn == 4:
print u'割り算開始'
print num_1 / num_2
else:
print u'不明なオペレーション指定です'
test_func(100, 10, 3)
--実行結果--
掛け算開始 1000
複数の引数を設定する場合は「 , 」(カンマ)で区切ります。上記の例では「100と10の掛け算を行う」というものでした。
引数は初期値を指定すると、関数を呼び出す際に省略する事が可能です。今回は第三引数の初期値を「1」と設定し、第三引数の指定無しで呼び出された場合は足し算をするようにしました。
# -*- coding: utf-8 -*-
def test_func(num_1, num_2, oprn=1):
if oprn == 1:
print u'足し算開始'
print num_1 + num_2
elif oprn == 2:
print u'引き算開始'
print num_1 - num_2
elif oprn == 3:
print u'掛け算開始'
print num_1 * num_2
elif oprn == 4:
print u'割り算開始'
print num_1 / num_2
else:
print u'不明なオペレーション指定です'
test_func(100, 10)
--実行結果--
足し算開始 110
もちろん第三引数の指定を行えば、その通りの処理をしてくれます。
# -*- coding: utf-8 -*-
def test_func(num_1, num_2, oprn=1):
if oprn == 1:
print u'足し算開始'
print num_1 + num_2
elif oprn == 2:
print u'引き算開始'
print num_1 - num_2
elif oprn == 3:
print u'掛け算開始'
print num_1 * num_2
elif oprn == 4:
print u'割り算開始'
print num_1 / num_2
else:
print u'不明なオペレーション指定です'
test_func(100, 10, 4)
--実行結果--
割り算開始 10
Pythonでは関数とメソッドがあります。特に意識する必要はありませんが、モジュール内に「def」で定義されているものが「関数」、クラス内に「def」で定義されているものが「メソッド」になります。
# -*- coding: utf-8 -*-
# 関数
def test_func():
print 'call test_func'
class TestClass:
# メソッド
def test_method():
print 'call test_method'
引数は奥が深い!
▶応用編:可変長引数
