4

公式计算

看到统计系统的代码往往很罗嗦,写了个小函数,可以一定程度上将逻辑集中,将公式抽取到配置文件中。
有兴趣的朋友可以继续阅读有关闭包的内容。

?Download expr.py
# encoding: utf8
"""
Expr module
"""
import types
def calc(formula, *args):
    """
    使用给定的参数计算公式的值.
    @formula: 公式,用'#' 作为参数占位符,比如'#+#',表示两个数相加
    @*args: 参数列表,参数可以是函数
    例子:
    - 数值参数:calc('#+#', 1, 1),结果为2
    - 函数参数:calc('#-#', time.time, time.time),结果为0
    """
    parts = []
    pos = 0
    for c in formula:
        if c is '#':
            if pos >= len(args):
                raise Exception('Index out of range. \
                        The formula need more arguments')
            part = args[pos]
            if callable(part):
                part = part()
            part = str(float(part))
            pos += 1
        else:
            part = c
        parts.append(part)
    return eval(''.join(parts))
 
if __name__ == '__main__':
    """
    Sample unit test
    """
    import time
    assert 0 == calc('#-#', time.time, time.time) 
    assert 2 == calc('#+#', 1, 1)
    print 'Cool! All cases passed.'

- 相关文章:

  • ⋯⋯⋯⋯
  1. 周波 says:

    代码插件很牛啊!!!

  2. wangchen [weibo] says:

    你这是变向夸自己啊!

  3. li3huo says:

    插件哪里下?

login with sina weibo