gpt4 book ai didi

python - 如何存储相同的参数以供多个函数使用

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:37 24 4
gpt4 key购买 nike

我有多个函数将使用相同的参数。是否可以只将参数存储到一个变量中,以便我可以将该变量传递给多个函数?

例子:

#Store the arguments into a variable:
Arguments = (pos_hint={'center_x': 0.5, 'center_y': 0.5},
size_hint=(1, 1), duration=2) #possible?


function1(Arguments) #Then pass variable to first function
function2(Arguments) #Then pass variable to different function
function3(Arguments) #etc.
...

最佳答案

您可以将参数存储在字典中,然后使用 ** unpacking syntax :

Arguments = {
'pos_hint': {'center_x': 0.5, 'center_y': 0.5},
'size_hint': (1, 1),
'duration': 2
}

function1(**Arguments)
function2(**Arguments)
function3(**Arguments)

下面是一个演示:

>>> def func(a, b, c):
... return a + b + c
...
>>> dct = {'a':1, 'b':2, 'c':3}
>>> func(**dct)
6
>>>

基本上,做:

func(**dct)

相当于:

func(a=1, b=2, c=3)

关于python - 如何存储相同的参数以供多个函数使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26922796/

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