如何实现具有非本地相等性的Decorator?

时间:2008-09-24 15:08:50

标签: python decorator multiple-inheritance

问候,目前我正在重构我的一个程序,我发现了一个有趣的问题。

我在自动机中有过渡。转换始终具有开始状态和结束状态。某些Transitions有一个标签,它编码必须在遍历时执行的某个Action。没有标签意味着没有行动。某些转换具有一个条件,必须满足该条件才能遍历此条件,如果没有条件,转换基本上是NFA中的epsilon转换,并且将在不消耗输入符号的情况下遍历。

我需要以下操作:

  • 检查过渡是否有标签
  • 获取此标签
  • 为过渡添加标签
  • 检查过渡是否有条件
  • 得到这个条件
  • 检查是否平等

从前五点来看,这听起来像一个清晰的装饰,有一个基础过渡和两个装饰:标签和条件。但是,这种方法存在一个问题:如果两个转换的起始状态和结束状态相同,两个转换处的标签相同(或不存在)且两个条件相同(或不存在),则认为两个转换相等。使用装饰器,我可能有两个过渡标签(“foo”,条件(“bar”,过渡(“baz”,“qux”)))和条件(“bar”,标签(“foo”,过渡(“baz”) “,”qux“)))需要非局部相等,即装饰者需要收集所有数据,而过渡必须在集合基础上比较这些收集的数据:

class Transition(object):
    def __init__(self, start, end):
        self.start = start
        self.end = end
    def get_label(self):
        return None
    def has_label(self):
        return False
    def collect_decorations(self, decorations):
        return decorations
    def internal_equality(self, my_decorations, other):
        try:
            return (self.start == other.start
                    and self.end == other.end
                    and my_decorations = other.collect_decorations())
    def __eq__(self, other):
        return self.internal_equality(self.collect_decorations({}), other)

class Labeled(object):
    def __init__(self, label, base):
        self.base = base
        self.label = label
    def has_label(self):
        return True
    def get_label(self):
        return self.label
    def collect_decorations(self, decorations):
        assert 'label' not in decorations
        decorations['label'] = self.label
        return self.base.collect_decorations(decorations)
    def __getattr__(self, attribute):
        return self.base.__getattr(attribute)

这是一种干净的方法吗?我错过了什么吗?

我很困惑,因为我可以用更长的类名来解决这个问题 - 使用合作多重继承:

class Transition(object):
    def __init__(self, **kwargs):
        # init is pythons MI-madness ;-)
        super(Transition, self).__init__(**kwargs)
        self.start = kwargs['start']
        self.end = kwargs['end']
    def get_label(self):
        return None
    def get_condition(self):
        return None
    def __eq__(self, other):
        try:
            return self.start == other.start and self.end == other.end
        except AttributeError:
            return False

class LabeledTransition(Transition):
    def __init__(self, **kwargs):
        super(LabeledTransition).__init__(**kwargs)
        self.label = kwargs['label']
    def get_label(self):
        return self.label
    def __eq__(self):
        super_result = super(LabeledTransition, self).__eq__(other)
        try:
            return super_result and self.label == other.label
        except AttributeError:
            return False

class ConditionalTransition(Transition):
    def __init__(self, **kwargs):
        super(ConditionalTransition, self).__init__(**kwargs)
        self.condition = kwargs['condition']

    def get_condition(self):
        return self.condition

    def __eq__(self, other):
        super_result = super(ConditionalTransition, self).__eq__(other)
        try:
            return super_result and self.condition = other.condition
        except AttributeError:
            return False

# ConditionalTransition about the same, with get_condition
class LabeledConditionalTransition(LabeledTransition, ConditionalTransition):
    pass

类LabledConditionalTransition的行为完全符合预期 - 并且没有代码在那里是吸引人的,我不会在这个大小混淆MI。

当然,第三种选择就是将所有内容都放入一个过渡类中,其中包含一堆has_label / has_transition。

所以...我很困惑。我错过了什么吗?哪种实现看起来更好?你如何处理类似的情况,即看起来像装饰器的对象可以处理它们,但是,这样的非本地方法到来了?

修改的: 添加了ConditionalTransition类。基本上,这种行为类似于装饰器,减去创建装饰器的顺序创建的顺序,开始和结束的转换检查是正确的,LabeledTransition类检查标签是否正确,ConditionalTransition检查条件是否正确。

2 个答案:

答案 0 :(得分:2)

我认为很明显没有人真正了解你的问题。我建议把它放在上下文中并缩短它。作为一个例子,这里是python中状态模式的一种可能实现,请研究它以获得一个想法。

class State(object):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name

class Automaton(object):
    def __init__(self, instance, start):
        self._state = start
        self.transitions = instance.transitions()

    def get_state(self):
        return self._state

    def set_state(self, target):
        transition = self.transitions.get((self.state, target))
        if transition:
            action, condition = transition
            if condition:
                if condition():
                    if action:
                        action()
                    self._state = target
            else:
                self._state = target
        else:
            self._state = target

    state = property(get_state, set_state)

class Door(object):
    open = State('open')
    closed = State('closed')

    def __init__(self, blocked=False):
        self.blocked = blocked

    def close(self):
        print 'closing door'

    def do_open(self):
        print 'opening door'

    def not_blocked(self):
        return not self.blocked

    def transitions(self):
        return {
            (self.open, self.closed):(self.close, self.not_blocked),
            (self.closed, self.open):(self.do_open, self.not_blocked),
        }

if __name__ == '__main__':
    door = Door()
    automaton = Automaton(door, door.open)

    print 'door is', automaton.state
    automaton.state = door.closed
    print 'door is', automaton.state
    automaton.state = door.open
    print 'door is', automaton.state
    door.blocked = True
    automaton.state = door.closed
    print 'door is', automaton.state

该程序的输出将是:

door is open
closing door
door is closed
opening door
door is open
door is open

答案 1 :(得分:0)

从发布的代码中,Transition和Labeled Transition之间的唯一区别是get_lable()和has_label()的返回。在这种情况下,您可以将这两个压缩为一个将label属性设置为None和

的类
return self.label is not None
<_>在has_label()函数中。

您可以发布ConditionalTransition课程的代码吗?我认为这会更清楚。