この記事では、Pythonで関数を引数として渡すためのさまざまな方法について説明します。
Pythonの関数とは?
Pythonのプログラミングでは、関数が非常に重要な役割を果たします。
Pythonでは、さまざまな種類の関数を幅広く、豊富に取り揃えています。
Pythonの関数は、モジュール化機能を提供します。
つまり、関数を使うことで、1つの大きなPythonコードのブロックを小さなブロックに分割し、それぞれのブロックが特定のタスクを実行するようにすることができるのです。
Pythonでは、あらかじめ定義された関数を使用することもできますし、独自の関数を定義することもできます。
特定のクラスの中で定義された関数は、Pythonではメソッドと呼ばれます。
ファーストクラスオブジェクトとしてのファンクション
ファーストクラスオブジェクトとは、プログラム全体で統一的に扱われるオブジェクトのことです。
つまり、ファーストクラスオブジェクトは変数に格納したり、関数の引数として渡したり、制御文の中で使用したりすることができます。
Pythonはファーストクラスオブジェクトの概念をサポートし、関数をファーストクラスオブジェクトとして扱います。
このような理由から、Pythonでは関数を他の関数に引数として渡すことができるのです。
Pythonで関数を引数として渡すには?
Pythonでは、以下の方法でさまざまな種類の関数を別の関数に引数として渡すことができます。
それでは、一つずつ説明していきます。
1. ユーザー定義関数
Pythonでは、通常の変数と同じように、ユーザー定義関数を別の関数の引数として渡すことができます。
このように、他の関数を引数として受け取る関数を高階関数と呼びます。
それでは、Pythonのコードでどのように実装するかを見てみましょう。
# Define higher order functiondef fun(foo):
result = foo('Welcome To Python!!')
return result
# Define function-1def fun1(str):
return str.lower()
# Define function-2def fun2(str):
return str.upper()
# Pass funtion-1 as an argument# to fun() functionstr1 = fun(fun1)
print(str1)
# Pass funtion-2 as an argument# to fun() functionstr2 = fun(fun2)
print(str2)
|
結果は以下の通りです。
welcome to askpython!! WELCOME TO ASKPYTHON!! |
2. クラスメソッド
ユーザー定義関数と同じように、クラスメソッドも引数として渡すことができます。
Pythonで2つのメソッドを持つクラスを定義し、このクラスのオブジェクトを作成して、それらのメソッドを呼び出してみましょう。
これを実装するためのPythonのコードを見てみましょう。
# Define a Python classclass demo_class:
# Define method-1
def method1(self):
print("Method-1 Running")
return "Python!!"
# Define method-2
def method2(self, foo):
print("Method-2 Running")
result = foo()
return result
# Create a demo_class object# using the class constructorobj = demo_class()
# Pass method-1 as an argument to method-2str = obj.method2(obj.method1)
print(str)
|
結果は以下の通りです。
Method-2 Running Method-1 Running Python!! |
この記事もチェック:Pythonでメモ化の実装|関数やクラス、デコレーターを使った方法を解説
3. ラムダ関数
Pythonにおいて、ラムダ関数はラムダ式を評価した際に返される関数オブジェクトです。
ユーザー定義関数やクラスメソッドと同様に、ラムダ関数も他の関数の引数として渡すことができます。
これを実装するためのPythonのコードを見てみましょう。
# Create a Python listls = [1, 2, 3, 4, 5]
print('This is the given list:')
print(ls)
# Pass lambda function # to map() function to claculate# the square of each list elementiter_obj = map((lambda n: n**2), ls)
# Construct the list again with# square of the elements of the given listls = list(iter_obj)
print('This is the final list:')
print(ls)
|
結果は以下の通りです。
This is the given list: [1, 2, 3, 4, 5] This is the final list: [1, 4, 9, 16, 25] |
4. 演算子関数
Pythonでは、あらかじめ定義された関数を含むoperatorモジュールがあります。
これらの関数により、与えられた引数のリストに対して数学的、関係論的、論理的、またはビット演算を実行することができます。
ユーザー定義関数やラムダ関数と同様に、演算子関数を他の関数への引数として渡すこともできます。
ここでは、operatorモジュールの operator.mul() 関数を使用して、Pythonのリストと一緒にfunctoolsモジュールで定義されている reduce() 関数に渡します。
これにより、渡されたリストの要素の積が計算されて返されます。
これをPythonのコードで実装してみましょう。
# Importing Python functools module which contains the reduce() functionimport functools
# Importing Python operator module which contains the mul() functionimport operator
# Defining a Python listls = [1, 3, 5, 7, 9, 11]
print("Given Python list:")
print(ls)
# Pass the mul() function as an argument # to the reduce() function along with the listls_product = functools.reduce(operator.mul, ls)
# Printing the resultsprint("Product of the given Python list: ", ls_product)
|
結果は以下の通りです。
Given Python list: [1, 3, 5, 7, 9, 11] Product of the given Python list: 10395 |
5. ビルトイン関数
Pythonには、list()、tuple()、dict()、str()など、非常に多くの標準的な組み込み関数が用意されています。
ユーザー定義関数と同様に、Pythonでもビルトイン関数を引数として別の関数に渡すことができます。
ここでは、文字列と数値からなるPythonのタプルと共に str() 関数を map() 関数に渡してみます。
str.join()関数は、与えられたタプルをPythonの文字列に変換するために使用します。
では、これを実装するPythonのコードを書いてみましょう。
# Create a Python tupletup = ('Linux', 'Ubuntu', 20.04)
print("Given Python tuple:")
print(tup)
# Pass the str() function# to the map() functioniter_obj = map(str, tup)
# Construct the string from # the returned iterator object# of the given tuplestr1 = "-".join(iter_obj)
# Print the resultprint("Generated Python string from tuple:")
print(str1)
|
結果は以下の通りです。
Given Python tuple: ('Linux', 'Ubuntu', 20.04) Generated Python string from tuple: Linux-Ubuntu-20.0 |
まとめ
この記事では、以下のことを学びました。
- ファーストクラスオブジェクトとは何か?
- ユーザー定義関数を引数として渡すには?
- クラスメソッドを引数として渡すには?
- ラムダ関数を引数として渡すには?
- 演算子関数を引数として渡すには?
- 引数として組み込み関数を渡す方法?
Pythonの関数についてもっと学び、探検する準備ができていることを願っています。