简体   繁体   中英

Python - Construct a variable name based on function argument

def my_func(arg):
    ...
    x = foo(var_arg)
    ...

With many variables saved as var_1 , var_2 , var_3 I would be able to pass one of them based on the foo function's argument. So if I call my_func(2) , in the function x will equal the result of foo(var_2) . Is it possible to construct a variable name like you would with strings?

How about using a dictionary for storing the variables and then dynamically constructing variable names based on the arguments passed and then accessing the corresponding values, which can then be passed on as argument to function foo

In [13]: variables = {"var_1" : 11, "var_2": 22, "var_3": 33} 
    ...:  
    ...: def my_func(arg): 
    ...:     full_var = "var_" + str(arg)
    ...:     print(variables[full_var])
    ...:     # or call foo(variables[full_var])    
In [14]: my_func(1)                                                      
11

In [15]: my_func(2)
22

In [16]: my_func(3)
33

What I recommend you do is to use dictionaries. In my view, that would be the most efficient option. For example, pretend var_1 , var_2 , and var_3 equal 'a' , 'b' , and 'c' respectively. You'd then write:

d = {1: 'a', 2: 'b', 3: 'c'}

def foo(var):
    return d[var]

def my_func(arg):
    x = foo(var_arg)
    return x

my_func(1) # returns: 'a'

As you can see, you really don't even need variables when using the dictionary. Just use the value directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM