简体   繁体   中英

Many similar functions that do slightly different things

I have nine very similar functions, which do slightly different things. They all take the same inputs, and return the same type of outputs after performing similar arithmetic on them. As a very simple by parallel example, consider basic mathematical computations: addition, subtraction, multiplication, division, modulo, etc. all which take 2 inputs and produce one output. Let's say that some outside force controls which operation to apply, as below:

def add(a, b):
    return a+b

def sub(a, b):
    return a-b

def mul(a, b):
    return a*b

....

# Emulating a very basic switch-case
cases = {'a' : add,
         's' : sub,
         'm' : mul,
         'd' : div,
         ...
         ...      }

# And the function call like so (`choice` is external and out of my control):
cases[choice](x, y)

Is there a nice way to package all of those functions together (mainly to avoid writing similar docstrings for all :-P)? Actually, is there a better way to code the above functionality, in general?

Dependent on how large these other methods are, you could package them all together in one method and use lambda in the switch statement.

def foo(a, b, context):
    """ Depending on context, perform arithmetic """
    d = {
       'a': lambda x, y: x + y,
       's': lambda x, y: x - y,
       ..
    }
    return d[context](a, b)

foo(x, y, choice)

That puts it all in one method and avoids the several docstrings.

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