Reputation:
Is it possible to insert an operation (e.g *
, +
) between two variables at runtime?
My solution without doing this is multiple if, elif statements, but I don't think that's the most efficient way to do it.
EDIT: What I meant is I get two integers, and I want to apply an operation on one of them with the other, e.g x * y
, but I want to change *
to another operator (maybe they're called functions? Not sure) e.g -
, +
,^
based on input.
Does that make sense? Basically think of it as a calculator.
Upvotes: 2
Views: 280
Reputation: 1
If your list of operators is small enough you can probably use lambdas.
def operator_factory(op):
if op == '+':
return lambda x,y: x + y
elif op == '-':
return lambda x,y: x - y
elif op == '*':
return lambda x,y: x * y
elif op == '/':
return lambda x,y: x / y
elif op == '^':
return lambda x,y: x ^ y
Your if statements can depend on user input. Then you just use this like so:
>>> f = operator_factory('+')
>>> f(2,3)
5
Upvotes: 0
Reputation: 395045
To answer the follow-on question, for example, you can subclass int and then implement __xor__
to exponentiate instead of apply a bitwise or, which is called by the ^
operator:
import operator
class MyInt(int):
def __xor__(self, other):
return operator.pow(self, other)
and then:
>>> i = MyInt(2)
>>> i
2
>>> type(i)
<class '__main__.MyInt'>
>>> j = 3
>>> i^j
8
Upvotes: 1
Reputation: 64318
@AaronHall's is the answer you're looking for, but for completeness, I'd mention you can also use eval
.
var_1 = 2
var_2 = 3
op = '+'
print eval('%s%s%s' % (var_1, op, var_2))
However, eval is evil, so either don't use it, or use with caution.
Upvotes: 4
Reputation: 395045
I'm not sure if this is what you're looking for but the operator module has a lot of operations, e.g. add
and mul
(multiply):
import operator
var_1 = 2
var_2 = 3
print(operator.add(var_1, var_2))
print(operator.mul(var_1, var_2))
will print
5
6
Upvotes: 5