Python: make a variable equal to the operator (+, /, *, -)

Is it possible to assign a maths operator to a variable?

this is what I have, just a sample (typed it now, so don't worry about simple mistakes)

if image == "lighten":
    red_channel = red_channel + 50
else:  // image is darken
    red_channel = red_channel  - 50

Notice how I repeat the same code with a different statement. Is it possible to achieve something like this:

if (image == "lighten"):
    operator = +
else:
    operator = - 

red_channel = red_channel operator 50
+1
source share
3 answers
import operator
if (image == 'lighten'):
    op = operator.add
else:
    op = operator.sub

red_channel = op(red_channel, 50)

Or, if you have several possible operations,

op = {
    'lighten':operator.add,
    'darken':operator.sub,
     ...
    }
red_channel = op[image](red_channel,50)
+6
source

I like the built-in expressions, so:

red_channel += 50 if image == 'lighten' else -50
+2
source

, , 50 50:

red_channel = red_channel + (flag * 50)

"flag" 1 -1; 50 -50. , , .

+1

All Articles