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)
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)
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)
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)
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)
適用於向下相容
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
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