我有多个函数将使用相同的参数。是否可以只将参数存储到一个变量中,以便我可以将该变量传递给多个函数?
例子:
#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/