0
0

More than 3 years have passed since last update.

Pythonでメソッドの多重定義:TypingのUnionと、typeによる引数の型判定の組合せで実装可能

Last updated at Posted at 2020-12-02

問題意識

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]: 

( 参考 )

以下も参考になります。

teratail 「pythonで同じ名前の関数で引数が異なるもの」

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0