write a recognizer

Chunming Luo chunming.luo at synopsys.COM
Thu Feb 12 05:54:50 EST 2004


Peter Otten wrote:

>Klaus Neuner wrote:
>
>  
>
>>Hello,
>>
>>I want to write a class Recognizer, like so:
>>
>>class Recognizer(object):
>>
>>    def is_of_category_1(self, token):
>>        if token == 1:
>>            return "1"
>>        else:
>>            return False
>>
>>    def is_of_category_2(self, token):
>>        if token == 2:
>>            return "2"
>>        else:
>>            return False
>>
>>    def recognize(self, token):
>>        for fun in <?>:
>>            result = apply(fun, token)
>>            if result:
>>                return result
>>        return False
>>
>>What do I have to write instead of <?>?
>>Or: How should I design the recognizer, if the above design is not good?
>>
>>Klaus
>>    
>>
>
>The following assumes that all category checker method names start with a
>common prefix. Those are automatically extracted in the __init__() method.
>If you are interested in this technique, I stole it from cmd.py in the
>library. IIRC, the implementation is more complete as it also inspects the
>base classes.
>
>class Recognizer(object):
>    def __init__(self):
>        r = self.recognizers = []
>        for n in dir(self.__class__):
>            if n.startswith("is_"):
>                r.append(getattr(self, n))
>
>    def is_of_category_1(self, token):
>        if token == 1:
>            return "1"
>
>    def is_of_category_2(self, token):
>        if token == 2:
>            return "2"
>
>    def recognize(self, token):
>        # would also work:
>        #for fun in [self.is_of_category_1, self.is_of_category_2]:
>
>        for fun in self.recognizers:
>            result = fun(token)
>            if result:
>                return result
>        return False
>
>if __name__ == "__main__":
>    r = Recognizer()
>    for t in "12341":
>        print r.recognize(int(t)),
>    print
>
>Peter
>

Here is another solution:

        def recongnize(self, token):
                for item in self.__class__.__dict__.keys():
                        method = self.__class__.__dict__[item]
                        if callable(method) and method != 
self.__class__.__dict__["recongnize"]:
                                result = method(self, token)
                                if result:
                                        return result
                return false

-Chunming





More information about the Python-list mailing list