gpt4 book ai didi

Python:kwargs.pop() 和 kwargs.get() 之间的区别

转载 作者:太空狗 更新时间:2023-10-29 17:55:17 43 4
gpt4 key购买 nike

两种方法我都见过,但我不明白它们的区别以及我应该将什么作为“最佳实践”:

def custom_function(**kwargs):
foo = kwargs.pop('foo')
bar = kwargs.pop('bar')
...

def custom_function2(**kwargs):
foo = kwargs.get('foo')
bar = kwargs.get('bar')
...

最佳答案

get(key[, default]): return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

d = {'a' :1, 'c' :2}
print(d.get('b', 0)) # return 0
print(d.get('c', 0)) # return 2

pop(key[, default]) if key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

d = {'a' :1, 'c' :2}
print(d.pop('c', 0)) # return 2
print(d) # returns {'a': 1}
print(d.get('c', 0)) # return 0

注意:关于最佳实践问题,我会说这取决于您的用例,但我会默认使用 .get 除非我确实需要 .pop

关于Python:kwargs.pop() 和 kwargs.get() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49218302/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com