Dictionary or If statements, Jython

前端 未结 5 570
清酒与你
清酒与你 2021-01-06 06:04

I am writing a script at the moment that will grab certain information from HTML using dom4j.

Since Python/Jython does not have a native switch stat

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-06 06:30

    To avoid specifying the tag and handler in the dict, you could just use a handler class with methods named to match the type. Eg

    class  MyHandler(object):
        def handle_extractTitle(self, dom):
            # do something
    
        def handle_extractMetaTags(self, dom):
            # do something
    
        def handle(self, type, dom):
            func = getattr(self, 'handle_%s' % type, None)
            if func is None:
                raise Exception("No handler for type %r" % type)
            return func(dom)
    

    Usage:

     handler = MyHandler()
     handler.handle('extractTitle', dom)
    

    Update:

    When you have multiple arguments, just change the handle function to take those arguments and pass them through to the function. If you want to make it more generic (so you don't have to change both the handler functions and the handle method when you change the argument signature), you can use the *args and **kwargs syntax to pass through all received arguments. The handle method then becomes:

    def handle(self, type, *args, **kwargs):
        func = getattr(self, 'handle_%s' % type, None)
        if func is None:
            raise Exception("No handler for type %r" % type)
        return func(*args, **kwargs)
    

提交回复
热议问题