简体   繁体   中英

Python methods and “switches”

I'm trying to use a dictionary as a switch statement as in

def add(first, second):
    return first + second

def sub():
    ...
    return something

operations = {
    "Add": add,
    "Sub": sub
}

ret_val = operations[operation]

Now how can I pass the arguments to add and sub and get their response? Currently, I don't pass anything to the methods, and testing the ret_val. What I see is the operation getting called, but the return doesn't come back. What I get is the pointer to the operation method.

Thanks!

To call a function, put the arguments in parentheses after it, just like when you call a function directly by its name.

ret_val = operations[operation](1, 2)

Note that for this to work properly, all the functions in operations need to take the same number of arguments. So it won't work if add() takes two arguments but sub() takes none, as you've shown.

If the functions can take different numbers of arguments, you could put the arguments in a list and use the unpacking operator.

args = (1, 2)
ret_val = operations[operation](*args)

Then you just have to ensure that args contains the appropriate number of arguments for the particular operation.

The dictionary contains callable functions. To call them, just add the arguments in parentheses.

operations[operation](arg1, ...)

So, the main thing you're missing is executing the function call. The code as provided grabs the function reference properly, but you need parens to execute it.

Once you execute it, you need some way to pass arguments. Because the number of args varies by function, the best way is to pass both a variable number of args list ( *args ) and a dictionary of keyword arguments ( **kwargs ).

I've filled in your pseudocode slightly so these run:

def add(first, second):
    return first + second

def sub(first, second):
    return first - second

operations = {
    "Add": add,
    "Sub": sub,
}

Call add with args:

op = 'Add'
op_args = [1, 2]
op_kwargs = {}
ret_val = operations[operation](*op_args, **op_kwargs)
print(ret_val)

3

Call add with kwargs:

op = 'Add'
op_args = []
op_kwargs = {'first': 3, 'second': 4}
ret_val = operations[operation](*op_args, **op_kwargs)
print(ret_val)

7

If you try to pass both args and kwargs in a conflicting way, it will fail:

# WON'T WORK
op = 'Add'
op_args = [1, 2]
op_kwargs = {'first': 3, 'second': 4}
ret_val = operations[operation](*op_args, **op_kwargs)
print(ret_val)

TypeError: add() got multiple values for argument 'first'

But you can use both in a complementary way:

op = 'Add'
op_args = [1]
op_kwargs = {'second': 4}
ret_val = operations[operation](*op_args, **op_kwargs)
print(ret_val)

5

One technical note is that the naming args and kwargs is purely convention in Python. You could call them whatever you want. An answer that discusses the two more is available here: https://stackoverflow.com/a/36908/149428 .

Note that I did not do any input validation, etc for the purpose of a simple, focused answer. If you're getting input from a user, that's an important step to remember.

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