小书,在我以前作数据库的连接时,就用了这个工厂方法的。

归纳总结一下,更有利于成长吧。

import xml.etree.ElementTree as etree
import json

class 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.data

class XMLConnector:

    def __init__(self, filepath):
        self.tree = etree.parse(filepath)

    @property
    def parsed_data(self):
        return self.tree

def connection_factory(filepath):
    if filepath.endswith('json'):
        connector = JSONConnector
    elif filepath.endswith('xml'):
        connector = XMLConnector
    else:
        raise ValueError('Can not 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 factory

def main():
    sqlite_factory = connect_to('person.sq3')

    xml_factory = connect_to('person.xml')
    xml_data = xml_factory.parsed_data
    liars = xml_data.findall(".//{}[{}='{}']".format('person',
                                                     'lastName', 'Smith'))
    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))

    json_factory = connect_to('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']))

if __name__ == '__main__':
    main()
                  

最新文章

  1. 整理常用加密 iOS 与 Android 加密 MD5-SHA1
  2. Python学习笔记1-数据类型
  3. [python]爬虫学习(二)
  4. Scala学习(二)
  5. CSS 魔法系列:纯 CSS 绘制图形(各种形状的钻石)
  6. IE8中给HTML标签负值报错问题
  7. 【BZOJ-1912】patrol巡逻 树的直径 + DFS(树形DP)
  8. C++ 内存管理与堆栈
  9. Loader Generator---loading图片生成器
  10. Android 和iOS中 Gesture 和 Touch
  11. 打印从1到最大的n位数
  12. Linux 下安装python软件包(pip、nose、virtualenv、distribute )
  13. Ajax-jQuery实现
  14. NMEA协议 上位机 C# (转)
  15. 初识flink
  16. UVa 712
  17. [POI2011]Śmieci
  18. PHP单点登陆
  19. 学习c++的五十条忠告
  20. PowerShell的初步学习

热门文章

  1. git更换 拉取推送地址
  2. Ansible2:主机清单
  3. (转)Tomcat配置调优与安全总结
  4. MySQL学习(二)——MySQL多表
  5. a标签伪元素选择器
  6. Spyder docstrings文档字符串的标准
  7. why inline functions must be put in header files?
  8. Jekens 配置多项目SCM GitLab+Jenkins持续集成环境
  9. Go学习中
  10. spring-boot-全局异常