4
公式计算
看到统计系统的代码往往很罗嗦,写了个小函数,可以一定程度上将逻辑集中,将公式抽取到配置文件中。
有兴趣的朋友可以继续阅读有关闭包的内容。
# 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.' |
代码插件很牛啊!!!
你这是变向夸自己啊!
插件哪里下?
叫wp-codebox,在plugins 里面可以直接搜到。