博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
工厂方法模式
阅读量:5167 次
发布时间:2019-06-13

本文共 1935 字,大约阅读时间需要 6 分钟。

 

 

import xml.etree.ElementTree as etreeimport jsonclass JSONConnector:    def __init__(self, filepath):        self.data = dict()        with open(filepath, mode='r', encoding='utf-8') as f:            self.data = json.load(f)    @property    def parsed_data(self):        return self.dataclass XMLConnector:    def __init__(self, filepath):        self.tree = etree.parse(filepath)    @property    def parsed_data(self):        return self.treedef connection_factory(filepath):    if filepath.endswith('json'):        connector = JSONConnector    elif filepath.endswith('xml'):        connector = XMLConnector    else:        raise ValueError('Cannot connect to {}'.format(filepath))    return connector(filepath)def connect_to(filepath):    factory = None    try:        factory = connection_factory(filepath)    except ValueError as ve:        print(ve)    return factorydef main():    sqlite_factory = connect_to('data/person.sq3')    print()    xml_factory = connect_to('data/person.xml')    xml_data = xml_factory.parsed_data    liars = xml_data.findall(".//{}[{}='{}']".format('person',                                                     'lastName', 'Liar'))    print('found: {} persons'.format(len(liars)))    for liar in liars:        print('first name: {}'.format(liar.find('firstName').text))        print('last name: {}'.format(liar.find('lastName').text))        [print('phone number ({})'.format(p.attrib['type']),               p.text) for p in liar.find('phoneNumbers')]    print()    json_factory = connect_to('data/donut.json')    json_data = json_factory.parsed_data    print('found: {} donuts'.format(len(json_data)))    for donut in json_data:        print('name: {}'.format(donut['name']))        print('price: ${}'.format(donut['ppu']))        [print('topping: {} {}'.format(t['id'], t['type'])) for t in donut['topping']]if __name__ == '__main__':    main()

  

转载于:https://www.cnblogs.com/andy9468/p/8414328.html

你可能感兴趣的文章