0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python to RubyAdvent Calendar 2021

Day 17

[py2rb] キーワード引数と可変長引数の組み合わせ

Last updated at Posted at 2022-01-26

はじめに

移植やってます。
( from python 3.7 to ruby 2.7 )

引数 (Python)

def func1(a, b, *args):
    print(a, b, args)

def func2(a, b=None, *args):
    print(a, b, args)

def func3(a=None, b=None, *args):
    print(a, b, args)

func1('A')
func2('A')
func3(b='A')

func1('A', 'B')
func2('A', 'B')
func3(b='A', a='B')

func1('A', 'B', 'C', 'D')
func2('A', 'B', 'C', 'D')
func3('B', 'A', 'C', 'D')

#output
TypeError: func1() missing 1 required positional argument: 'b'
A None ()
None A () 
A B ()    
A B ()    
B A ()    
A B ('C', 'D')
A B ('C', 'D')
B A ('C', 'D')

引数を工夫することにより様々な関数を利用することができます。

独習Python 330p

引数 (Ruby)

def func1(a, b, *args)
  p [a, b, args]
end

func1('A')
func1('A', 'B')
func1('A', 'B', 'C', 'D')

`func1': wrong number of arguments
["A", "B", []]
["A", "B", ["C", "D"]]

func1の動作は同じです。

def func2(a, b: nil, *args)
  p [a, b, args]
end

syntax error, unexpected `end', expecting end-of-input

キーワード引数と可変長引数を同時に使用するとシンタックスエラーになります。

def func2(a, b=nil, *args)
  p [a, b, args]
end

func2('A')
func2('A', 'B')
func2('A', 'B', 'C', 'D')

["A", nil, []]
["A", "B", []]        
["A", "B", ["C", "D"]]

デフォルト値付き引数と可変長引数であれば、エラーは発生しません。

def func3(a=nil, b=nil, *args)
  p [a, b, args]
end

func3(b='A')
func3(b='A', a='B')
func3('B', 'A', 'C', 'D')

["A", nil, []]
["A", "B", []]        
["B", "A", ["C", "D"]]

しかし、エラーは発生しませんが、順番が問題になることが想定されます。

可変長引数の**kwargsを利用して渡すのが現実的でしょうか。

メモ

  • 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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?