I want to do something like
class A:
def __init__( self, left, right, op ):
self.left = left
self.right = right
self.op = op
def calculate( self ):
self.number = op( self.left, self.right )
return self.number
and use it, for example, like this:
a = A( 1, 2, + )
a2 = A( 2, 3, * )
I tried to do
op = +
op = __add__
but none of these worked. Can somebody tell is this possible (and if it is, how this is called, because I don't even know how to search it). Or the only possible way is to have a big, ugly if-else statement in calculate and check the value of op, which will be stored as str?
Thanks!
See the operator module.
a = A( 1, 2, operator.add )
Another way to do this would be to supply a lambda function as the third parameter:
a = A( 1, 2, lambda x,y: x + y)
b = A( 1, 2, lambda x,y: x * y)
This would allow you to support more complex operations, not present in the operator module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With