开发者

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

开发者 https://www.devze.com 2023-02-28 14:47 出处:网络
I want to do something like class A: def __init__( self, left, right, op ): self.left = left sel开发者_如何学Pythonf.right = right

I want to do something like

class A:
    def __init__( self, left, right, op ):
        self.left = left
        sel开发者_如何学Pythonf.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.

0

精彩评论

暂无评论...
验证码 换一张
取 消