《精通Python设计模式》学习之工厂方法
2024-08-25 20:11:17
小书,在我以前作数据库的连接时,就用了这个工厂方法的。
归纳总结一下,更有利于成长吧。
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()
最新文章
- 整理常用加密 iOS 与 Android 加密 MD5-SHA1
- Python学习笔记1-数据类型
- [python]爬虫学习(二)
- Scala学习(二)
- CSS 魔法系列:纯 CSS 绘制图形(各种形状的钻石)
- IE8中给HTML标签负值报错问题
- 【BZOJ-1912】patrol巡逻 树的直径 + DFS(树形DP)
- C++ 内存管理与堆栈
- Loader Generator---loading图片生成器
- Android 和iOS中 Gesture 和 Touch
- 打印从1到最大的n位数
- Linux 下安装python软件包(pip、nose、virtualenv、distribute )
- Ajax-jQuery实现
- NMEA协议 上位机 C# (转)
- 初识flink
- UVa 712
- [POI2011]Śmieci
- PHP单点登陆
- 学习c++的五十条忠告
- PowerShell的初步学习