传递字典形式的多个参数给函数

huangapple go评论133阅读模式
英文:

Passing multiple arguments to a function with a dictionary

问题

我有一组函数fun1fun2fun3,我从一个主文件中调用它们。它们每个都使用在主文件中存储的一些变量(我也在那里调用这些函数):

a = 2
b = 3
c = 12
d = "abc"
e = 12
f = "jh4jer"
g = np.array([2, 3])

fun1(a, b, c, d, e, f)
fun2(d, e, f, g)
fun3(a, e, f, g)

我想创建一种结构(在我看来,字典是完美的)来存储所有的变量,所以我可以只传递这个字典给我的函数,就像这样:

dictionary1 = {'a': a, 'b': b, 'c': c, 'd': d, 'e': e, 'f': f, 'g': g}
fun1(dictionary1)
fun2(dictionary1)
fun3(dictionary1)

我可以这样做吗?还是有更聪明的方法?如果我传递给函数的参数多于所需的参数,会有问题吗?

英文:

I have a set of functions fun1, fun2, fun3 that I'm calling from a main file. Each of them are using some variables stored in my main file (where I'm also calling the functions):

a = 2
b = 3
c = 12
d = "abc"
e 12
f = "jh4jer"
g = np.array(2,3)

fun1(a,b,c,d,e,f)
fun2(d,e,f,g)
fun3(a,e,f,g)

I would like to create a sort of structure (in my opinion a dictionary would be perfect) to store all my variables to I can pass only this dictionary to my functions, something like that:

dictionary1 = {'a':a, 'b':b, 'c':c, 'd':d, 'e':e, 'f':f, 'g':g}
fun1(dictionary1)
fun2(dictionary1)
fun3(dictionary1)

Can I do something like that or there is a smarter way? Is it going to be an issue if I pass more arguments to a function with respect to the ones required?

答案1

得分: 1

你可以将整个字典传递给每个函数,然后在函数中只提取它需要的参数。例如:

var1 = 123
var2 = 'hello'
var3 = 456

d = {'a': var1, 'b': var2, 'c': var3}

def func1(x):
    print(x['a'])
    print(x['c'])

def func2(z):
    print(z['b'])

func1(d)
func2(d)
英文:

You can pass the whole dictionary to each function and just pick up in a function the arguments it requires. For example:

var1 = 123
var2 ='hello'
var3 = 456

d = {'a': var1, 'b': var2, 'c': var3}

def func1(x):
    print(x['a'])
    print(x['c'])
    
def func2(z):
    print(z['b'])
        
func1(d)
func2(d)

答案2

得分: 0

你可以尝试这种方式 -

obj: dict = {
    "a": 2, "b": 3, "c": 12, "d": "abc", "e": 12, "f": "jh4jer", "g": np.array(2,3)}

# 将整个对象传递给函数
fun1(obj)

# 仅向fun2传递所需的变量
fun2_obj = {"d": obj["d"], "e": obj["e"], "f": obj["f"], "g": obj["g"]}
fun2(fun2_obj)

# 仅向fun3传递所需的变量
fun3_obj = {"a": obj["a"], "e": obj["e"], "f": obj["f"], "g": obj["g"]}
fun3(fun3_obj)
英文:

You can try this way -

obj: dict = {
    "a": 2, "b": 3, "c": 12, "d": "abc", "e": 12, "f": "jh4jer", "g": np.array(2,3)}

# pass full object to function
fun1(obj)

# pass only required variables to fun2
fun2_obj = {"d": obj["d"], "e": obj["e"], "f": obj["f"], "g": obj["g"]}
fun2(fun2_obj)


# pass only required variables to fun3
fun3_obj = {"a": obj["a"], "e": obj["e"], "f": obj["f"], "g": obj["g"]}
fun3(fun3_obj)

huangapple
  • 本文由 发表于 2023年3月3日 19:28:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定