简体   繁体   English

每次我在Python中调用函数时,都会改变不同的参数

[英]Vary different parameters each time I call a function in Python

I have a function 我有一个功能

def input_definition(parameter_variation=None):

    input_def = {}
    input_def['a'] = 1
    input_def['b'] = 2
    input_def['c'] = 3
    ...
    input_def['z'] = 26

    # Apply the parameter variation by means of the input argument 'parameter_variation'.
    # ...

    # Save 'input_def' to external file with dill module.
    # ...

with many parameters. 有很多参数。 I want to vary some of these parameters by giving parameter_variation to the function input_definition . 我想通过给函数input_definition提供parameter_variation来改变其中一些参数。 I need to vary different parameters each time I call input_definition . 每次调用input_definition时,我都需要改变不同的参数。

So one time parameter_variation contains values for a and b and another time parameter_variation contains values for c and d . 因此,一个时间parameter_variation包含ab值,而另一个时间parameter_variation包含cd值。

What is the best / most neat / Pythonic way to do this? 什么是最好/最整洁/ Pythonic的方法? Or is it perhaps better to use kwargs? 还是使用kwargs更好?

You can use kwargs for this like so: 您可以这样使用kwargs

def some_func(**kwargs):
    my_dict = dict(
        a=1,
        b=2,
        c=3,
        d=4
    )
    my_dict.update(**kwargs)

This will set your defaults and then override them with kwargs. 这将设置您的默认值,然后用kwargs覆盖它们。

It is arguable better to give more limited inputs to the dict by simply using default arguments like so: 可以通过简单地使用默认参数为dict提供更多有限的输入,这是有争议的:

def some_func(a=1, b=2, c=3, d=4):
    my_dict = dict(
        a=a,
        b=b,
        c=c,
        d=d
    )

This is more secure and makes your intentions more understandable to someone reading your code. 这样更安全,并使您的意图对于阅读您的代码的人来说更容易理解。 But is less flexible in comparison to kwargs . 但与kwargs相比,灵活性较差。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过一个函数迭代一个结构两次,但每次使用不同的参数,而不在 python 中使用两个 for 循环? - How can I iterate a structure twice through a function, but with different parameters each time, without using two for loops in python? Python时间分析每个语句作为参数的函数 - Python time profiling each statement as a function of parameters Python:没有参数的函数,每次调用时都会返回一个不同且唯一的数字 - Python: a function without parameters that returns a different and unique number each time it is called 如何写一个大师function每次调用不同数量的函数? - How do I write a master function to call a different number of functions each time? 如何在Python中为动态系统随时间改变参数? - How can I vary a parameter over time for a dynamical system in Python? 如何在python中用不同的参数多次调用一个function? - How to call a single function multiple times with different parameters in python? 如何在 kivy 中随时间变化 function? - How to vary function with time in kivy? 每当我在一个类中调用一个函数时,都增加计数器 - increase counter each time i call a function within a class 我如何为每个函数调用获取不同的记录器? - How i can get different logger for each call of function? python函数调用的参数顺序 - order of parameters of function call of python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM