問題意識
Pythonでは、メソッドの多重定義(オーバーロード)をする機能が標準で付いていない。
そこで、TypingのUnionと、typeを用いた引数の型判定の組合わせで実装してみた。
実装コード
例として、配列(list)と文字列(str)を両方、引数として受け取ることができ、どちらを受け取ったかにより、異なる処理を行うメソッドを作成してみました。
ipython(Python3.9.0)
In [1]: from typing import Dict, Tuple, List, Union
In [2]: def sample_func(arg : Union[str, List]) -> str:
...: if type(arg) is list:
...: output_str = "\n".join(arg)
...: elif type(arg) is str:
...: output_str = arg
...: else:
...: output_str = ''
...:
...: return output_str
...:
挙動確認
(ケース1) 引数として配列listを渡す
ipython(Python3.9.0)
In [3]: sample_func(["1", "a", "b"])
Out[3]: '1\na\nb'
In [4]: print(sample_func(["1", "a", "b"]))
1
a
b
In [4]:
(ケース2) 引数として文字列strを渡す
ipython(Python3.9.0)
In [4]: sample_func("明日はアフォガードを食べよう。もう今日は寝るよ。")
Out[4]: '明日はアフォガードを食べよう。もう今日は寝るよ。'
In [5]: print(sample_func("明日はアフォガードを食べよう。もう今日は寝るよ。"))
明日はアフォガードを食べよう。もう今日は寝るよ。
In [6]:
( 参考 )
以下も参考になります。