Python **kwargs 的實測

 

Python **kwargs 的實測  

都必填

都有帶入值

def test_func(a1, a2): print(a1) print(a2) if __name__ == '__main__': d = dict() d['a1'] = 1 d['a2'] = 2 test_func(**d)

out put

1 2

有值未帶入

def test_func(a1, a2): print(a1) print(a2) if __name__ == '__main__': d = dict() d['a1'] = 1 test_func(**d)

out put

Traceback (most recent call last): File "xxx/main.py", line 44, in <module> test_func(**d) TypeError: test_func() missing 1 required positional argument: 'a2'

有預設值參數

def test_func(a1, a2=None): print(a1) print(a2) if __name__ == '__main__': d = dict() d['a1'] = 1 test_func(**d)

output

1 None

帶入沒有該參數的key & value (unexpected-keyword-arguments)

def test_func(a1, a2=None): print(a1) print(a2) if __name__ == '__main__': d = dict() d['a1'] = 1 d['a2'] = 2 d['a3'] = 3 test_func(**d)

output

Traceback (most recent call last): File "xxx/main.py", line 46, in <module> test_func(**d) TypeError: test_func() got an unexpected keyword argument 'a3'

解決unexpected-keyword-arguments 的作法

適用於向下相容

def test_func(a1, a2=None,**kwargs): print(a1) print(a2) print(kwargs['a3']) if __name__ == '__main__': d = dict() d['a1'] = 1 d['a2'] = 2 d['a3'] = 3 test_func(**d)

output

1 2 3




md

留言

  1. Gold Casino - Slot Machines - titanium band rings
    Gold Casino. Slot Machines | Slot how much is titanium worth Machines | Silver, Gold, Iron, Casino. Gold Casino. titanium wok Bronze-Gold. Iron-Gold. Gold Casino. Silver-Gold. titanium belly rings Gold Casino. titanium flat irons Gold Casino. titanium aftershokz Gold

    回覆刪除

張貼留言

這個網誌中的熱門文章

angular 如何Http 如何設定 CORS (Cross-Origin Resource Sharing)

Google Map 單車路徑計算坡度和角度小工具

Google URL Shortener API 快速教學