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

标签 python function python-2.7 arguments

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

例子:

#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/

相关文章:

python - Sphinx 和可重复使用的 Django 应用程序

python - 为什么 Dash-Plotly 应用程序中的 map 尺寸太小?

python - DataTable - 单元格中的唯一颜色子字符串

sql - 分割字符串后将值插入表中

python - 将不同的 raw_input 传递给正在 Python 中测试的函数

python - 尝试运行 TensorFlow 时的 CUDNN_STATUS_NOT_INITIALIZED

c++ - 有没有办法递归遍历矩阵的所有可能子矩阵,同时防止访问某些子矩阵?

c++ - C++中属性 vector 的查询

python - 无法使用 Windows 提示符运行 python 脚本文件

python - "no matching architecture in universal wrapper"导入pygame时