2

I have this piece of code.

def maths(operator):
   #different math here..

   final = final + number #i want to use the operator arg here

. Later on, i want to call it like maths('+') or maths('-'), so I don't have to use the same piece of code every time.

user3196332
  • 361
  • 2
  • 4
  • 11

2 Answers2

6

You are looking for the operator module

def maths(accum):
    #...
    final = accum(final, number):

x = maths(operator.mul)
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
3

There's probably a duplicate for this somewhere, but I can't think of it.

Here's how you'd do it -- you need to use the magic methods that those operators are shortcuts for!

def maths(operator):
    mapping = { "+": final.__add__,
                "-": final.__sub__,
                "x": final.__mul__,
                "*": final.__mul__,
                "/": final.__truediv__,
                "//": final.__floordiv__}
    return mapping[operator](number)

It's a big complicated, but basically the way those operators work under the hood is by calling a magic method as described here. You could make a "faux number" by doing:

class FakeNumber(object):
    def __init__(self, value=0):
        self.value = value
    def __add__(self,other):
        return self.value + other
    def __sub__(self,other):
        return self.value - other
    def __mul__(self,other):
        return self.value * other
    def __truediv__(self,other):
        return self.value / other
    def __floordir__(self,other):
        return self.value // other

Now that all your magic methods are implemented, you can do:

two = FakeNumber(2)
two * 4 # 8
two + 2 # 4
two / 2 # 1
two - 2 # 0
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • It says 'NameError: global name 'final' is not defined' – user3196332 Apr 28 '14 at 23:00
  • @user3196332 so does your code. I assumed you knew what `final` meant :) – Adam Smith Apr 28 '14 at 23:00
  • @user3196332 but a-ha! Someone found the duplicate and its answer is better than mine since it implements `operator` which uses an ABC (Abstract Base Class) to take two operators instead of one. That will work much better for you. – Adam Smith Apr 28 '14 at 23:01
  • OK i can see now what u mean. thank you! will accept answer in 5mins – user3196332 Apr 28 '14 at 23:03
  • @user3196332 no need to accept, the duplicate is a much better answer anyhow. Like as not this question will be closed in 5 minutes! :D – Adam Smith Apr 28 '14 at 23:05