Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign an operation like sum or substitute, etc., to a variable

Tags:

python

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!

like image 385
Kiril Kirov Avatar asked Jan 27 '26 22:01

Kiril Kirov


2 Answers

See the operator module.

a = A( 1, 2, operator.add )
like image 64
Lukáš Lalinský Avatar answered Jan 29 '26 13:01

Lukáš Lalinský


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.

like image 26
Steve Mayne Avatar answered Jan 29 '26 12:01

Steve Mayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!