zoukankan      html  css  js  c++  java
  • Python中的动态类

    Python中的动态类


    有这样一个需求,我有SegmentReaderPostagReaderConllReader这三个Reader,他们都继承于一个Reader类。在程序运行中,由用户通过segmentpostagconll决定读入哪一种数据,所以XReader的实例化也由用户决定。当然,我们可以写一连串的if判断,但是这往往不够美观。这里有一个python动态创建类的问题。

    Python中有个一函数globals()返回当前全局的符号表,如果已经import了这三个类,他们就会出现在全局的符号表中。

    from corpusproc.io import SegmentReader, PostagReader, ConllReader
    
    def createObject(className, * args):
        cls = globals()[className]
    
        if isinstance(cls, type) and isinstance(args[0], file):
            return cls(args[0])
        else:
            raise Exception("No such class")
    

    测试一下

    format = "segment"
    reader = createObject(format[0].upper() + format[1:])
    
    format = "unknown"
    reader = createObject(format[0].upper() + format[1:])
    # Raise Exception "No such class"
  • 相关阅读:
    topcoder srm 681 div1
    topcoder srm 683 div1
    topcoder srm 684 div1
    topcoder srm 715 div1
    topcoder srm 685 div1
    topcoder srm 687 div1
    topcoder srm 688 div1
    topcoder srm 689 div1
    topcoder srm 686 div1
    topcoder srm 690 div1 -3
  • 原文地址:https://www.cnblogs.com/timssd/p/7221094.html
Copyright © 2011-2022 走看看