python 规则执行
# *_*coding:utf-8 *_* # @Author : zyb class Rule: def __init__(self, condition, action): #初始化规则:两个函数,第一个函数成立返回True,执行第二个函数 self.condition = condition self.action = action def evaluate(self, facts): #评估规则:param facts: 事实字典 if self.condition(facts): self.action(facts) class Agenda: def __init__(self): self.rules = [] #添加规则到引擎 Rule 对象 def add_rule(self, rule): self.rules.append(rule) def run(self, facts): """运行规则引擎:param facts: 事实字典""" for rule in self.rules: rule.evaluate(facts) class Fact(dict): def __getattr__(self, name): return self.get(name,None) if __name__ == '__main__': # 第一个判断函数 def one_condition_one(facts): print('第一个判断函数:', facts) return False # 第一个执行函数 def one_condition_two(facts): print('第一个执行函数:', facts) # 创建规则引擎 engine = Agenda() # 添加规则 engine.add_rule(Rule(one_condition_one, one_condition_two)) y = Fact(x=6,y=7) x = {'x': 6, 'y': 7} # 运行规则引擎 engine.run(y) engine.run(x)