Dictionary or If statements, Jython

前端 未结 5 596
清酒与你
清酒与你 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:39

    The efficiency question is barely relevant. The dictionary lookup is done with a simple hashing technique, the if-statements have to be evaluated one at a time. Dictionaries tend to be quicker.

    I suggest that you actually have polymorphic objects that do extractions from the DOM.

    It's not clear how type gets set, but it sure looks like it might be a family of related objects, not a simple string.

    class ExtractTitle( object ):
        def process( dom ):
            return something
    
    class ExtractMetaTags( object ):
        def process( dom ):
            return something
    

    Instead of setting type="extractTitle", you'd do this.

    type= ExtractTitle() # or ExtractMetaTags() or ExtractWhatever()
    type.process( dom )
    

    Then, you wouldn't be building this particular dictionary or if-statement.

提交回复
热议问题