write a recognizer

max khesin max at NcOviSsPiAoMntech.com
Thu Feb 12 09:54:36 EST 2004


This is cool. Curious (my py object recall is a bit stale): would this 
solution work for a class that derives from Recognizer (and implements 
an 'is_' method)?

thanks,
max


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



More information about the Python-list mailing list