In what situation should the built-in 'operator' module be used in python?

前端 未结 6 2175
暖寄归人
暖寄归人 2020-12-23 19:44

I\'m speaking of this module: http://docs.python.org/library/operator.html

From the article:

The operator module exports a set of functions

6条回答
  •  感动是毒
    2020-12-23 20:18

    I cannot remember the exact use case but I had a requirement somewhere that needed to do some calculation dynamically and this could be using a different operator depending on where it came from.

    A very simple example is this:

    import operator
    
    def add_or_subtract(x, y, op):
        return op(x, y)
    
    x = 3
    y = 10
    o = operator.add #operator.sub
    
    add_or_subtract(x, y, o)
    

提交回复
热议问题