【问题标题】:Rolling my own extremely light weight 'event' system滚动我自己的极轻量级“事件”系统
【发布时间】:2014-09-26 20:00:38
【问题描述】:

我正在使用 Python 2.7,我想编写一个小型库,它是一种“事件系统”。基本上,我有字段对象(目前只有两个属性,但以后可能会改变)和包含字段的标准对象。

标准类被传递一个包含字段对象的表达式,并且标准类是字段的观察者,因此每当包含的字段属性之一(例如值等)发生变化时,它都会触发标准类重新评估自身检查表达式是否为真。

如果表达式的计算结果为真,那么 Criterion 类会做一些事情 - 现在可能会打印到屏幕上。

class Field(Object):
    def __init__(self, id, name, value):
        self.id = id
        self.name =  name
        self.value = value

    def set_value(newval):
        self.value = newval

    def __repr__(self):
        print self.id, self.name, self.value



# A criterion is constructed with an expression containing field objects
# It 'listens' to changes in the field attributes and reevaluates itself and checks if expression is now true
# When the expression is true, it prints to the console
class Criterion(Object):
    def __init__(self, express):
        parse_expression(express) # parses expression to get field objects (is this necessary?)
        self.fields = {}  # dictionary of fields


    # call back when one of the parsed and observed fields changes
    def upon_field_change(field):
        if eval_expression():
            # do something
            print "Criterion evaluated true upon field change: %s", field
            pass

    # evaluate expression with current field objects
    # returns boolean
    def eval_expression():
        pass


    # evaluates bolean True/False
    def __nonzero__():
        eval_expression()

上面的代码sn-p是我的头顶,我的问题是:

  1. 我是走在正确的道路上还是有更好的方法来做我想做的事情?
  2. 上面的代码有没有更好的写法?

【问题讨论】:

    标签: python events eval observer-pattern


    【解决方案1】:

    我认为你不应该重新发明轮子,有一个优秀的 Python 事件库 叫louie(之前是pydispatcher),就用它。它允许从 任何 Python 对象,并执行回调。它可以正确处理引用,并且 还有其他功能。

    例如,在您的场景中,louie 可用于将更改从 Field 对象发送到 Criterion 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多