开始慢慢学习这本书了。。Python编程实战:运用设计模式、并发和程序库创建高质量程序
没办法,不到设计模式,算法组合这些,在写大一点程序的时候,总是力不从心。。。:(
一开始可能要花很多时间来慢慢理解吧,,这毕竟和《大话设计模式》用的C#语言有点不太一样。。。
书上代码是3版本的,有些库的用法不一样,还要改回2.7的才可以测试。。:(

#!/usr/bin/env python3
# Copyright 漏 2012-13 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version. It is provided for
# educational purposes and is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
import os
import sys
import tempfile
def main():
if len(sys.argv) > 1 and sys.argv[1] == "-P": # For regression testing
create_diagram(DiagramFactory()).save(sys.stdout)
create_diagram(SvgDiagramFactory()).save(sys.stdout)
return
textFilename = os.path.join(tempfile.gettempdir(), "diagram.txt")
svgFilename = os.path.join(tempfile.gettempdir(), "diagram.svg")
txtDiagram = create_diagram(DiagramFactory())
txtDiagram.save(textFilename)
print("wrote", textFilename)
svgDiagram = create_diagram(SvgDiagramFactory())
svgDiagram.save(svgFilename)
print("wrote", svgFilename)
def create_diagram(factory):
diagram = factory.make_diagram(30, 7)
rectangle = factory.make_rectangle(4, 1, 22, 5, "yellow")
text = factory.make_text(7, 3, "Abstract Factory")
diagram.add(rectangle)
diagram.add(text)
return diagram
class DiagramFactory:
def make_diagram(self, width, height):
return Diagram(width, height)
def make_rectangle(self, x, y, width, height, fill="white",
stroke="black"):
return Rectangle(x, y, width, height, fill, stroke)
def make_text(self, x, y, text, fontsize=12):
return Text(x, y, text, fontsize)
class SvgDiagramFactory(DiagramFactory):
def make_diagram(self, width, height):
return SvgDiagram(width, height)
def make_rectangle(self, x, y, width, height, fill="white",
stroke="black"):
return SvgRectangle(x, y, width, height, fill, stroke)
def make_text(self, x, y, text, fontsize=12):
return SvgText(x, y, text, fontsize)
BLANK = " "
CORNER = "+"
HORIZONTAL = "-"
VERTICAL = "|"
class Diagram:
def __init__(self, width, height):
self.width = width
self.height = height
self.diagram = _create_rectangle(self.width, self.height, BLANK)
def add(self, component):
for y, row in enumerate(component.rows):
for x, char in enumerate(row):
self.diagram[y + component.y][x + component.x] = char
def save(self, filenameOrFile):
file = None if isinstance(filenameOrFile, str) else filenameOrFile
try:
if file is None:
#file = open(filenameOrFile, "w", encoding="utf-8")
file = open(filenameOrFile, "w")
for row in self.diagram:
#print "hahah"
print >>file,"".join(row)
finally:
if isinstance(filenameOrFile, str) and file is not None:
file.close()
def _create_rectangle(width, height, fill):
rows = [[fill for _ in range(width)] for _ in range(height)]
for x in range(1, width - 1):
rows[0][x] = HORIZONTAL
rows[height - 1][x] = HORIZONTAL
for y in range(1, height - 1):
rows[y][0] = VERTICAL
rows[y][width - 1] = VERTICAL
for y, x in ((0, 0), (0, width - 1), (height - 1, 0),
(height - 1, width -1)):
rows[y][x] = CORNER
return rows
class Rectangle:
def __init__(self, x, y, width, height, fill, stroke):
self.x = x
self.y = y
self.rows = _create_rectangle(width, height,
BLANK if fill == "white" else "%")
class Text:
def __init__(self, x, y, text, fontsize):
self.x = x
self.y = y
self.rows = [list(text)]
SVG_START = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"
width="{pxwidth}px" height="{pxheight}px">"""
SVG_END = "</svg>\n"
SVG_RECTANGLE = """<rect x="{x}" y="{y}" width="{width}" \
height="{height}" fill="{fill}" stroke="{stroke}"/>"""
SVG_TEXT = """<text x="{x}" y="{y}" text-anchor="left" \
font-family="sans-serif" font-size="{fontsize}">{text}</text>"""
SVG_SCALE = 20
class SvgDiagram:
def __init__(self, width, height):
pxwidth = width * SVG_SCALE
pxheight = height * SVG_SCALE
self.diagram = [SVG_START.format(**locals())]
outline = SvgRectangle(0, 0, width, height, "lightgreen", "black")
self.diagram.append(outline.svg)
def add(self, component):
self.diagram.append(component.svg)
def save(self, filenameOrFile):
file = None if isinstance(filenameOrFile, str) else filenameOrFile
try:
if file is None:
#file = open(filenameOrFile, "w", encoding="utf-8")
file = open(filenameOrFile, "w")
file.write("\n".join(self.diagram))
file.write("\n" + SVG_END)
finally:
if isinstance(filenameOrFile, str) and file is not None:
file.close()
class SvgRectangle:
def __init__(self, x, y, width, height, fill, stroke):
x *= SVG_SCALE
y *= SVG_SCALE
width *= SVG_SCALE
height *= SVG_SCALE
self.svg = SVG_RECTANGLE.format(**locals())
class SvgText:
def __init__(self, x, y, text, fontsize):
x *= SVG_SCALE
y *= SVG_SCALE
fontsize *= SVG_SCALE // 10
self.svg = SVG_TEXT.format(**locals())
if __name__ == "__main__":
main()

开始慢慢学习这本书了。。Python编程实战:运用设计模式、并发和程序库创建高质量程序的更多相关文章
- python经典书籍:Python编程实战 运用设计模式、并发和程序库创建高质量程序
Python编程实战主要关注了四个方面 即:优雅编码设计模式.通过并发和编译后的Python(Cython)使处理速度更快.高层联网和图像.书中展示了在Python中已经过验证有用的设计模式,用专家级 ...
- 学习ASP.NET Core Razor 编程系列十八——并发解决方案
学习ASP.NET Core Razor 编程系列目录 学习ASP.NET Core Razor 编程系列一 学习ASP.NET Core Razor 编程系列二——添加一个实体 学习ASP.NET ...
- 二、继续学习(主要参考Python编程从入门到实践)
操作列表 具体内容如下: # 操作列表 # 使用for循环遍历整个列表. # 使用for循环处理数据是一种对数据集执行整体操作的不错的方式. magicians = ['alice', 'david' ...
- Python 编程实战提高测试工作效率实例之svn 文件管理
#coding=utf-8 ''' Created on 2016年8月22日 @author:Tom Gao ''' importre importos importtime "" ...
- [置顶] 学习JDK源码:编程习惯和设计模式
编程习惯 1.用工厂方法替代构造函数 Boolean.valueOf() 通过一个boolean简单类型,构造Boolean对象引用. 优点:无需每次被调用时都创建一个新对象.同时使得类可以严格控制在 ...
- 学习笔记《Java多线程编程实战指南》三
3.1串行.并发与并行 1.串行:一件事做完接着做下一件事. 2.并发:几件事情交替进行,统筹资源. 3.并行:几件事情同时进行,齐头并进,各自运行直到结束. 多线程编程的实质就是将任务处理方式由串行 ...
- 学习笔记《Java多线程编程实战指南》二
2.1线程属性 属性 属性类型及用途 只读属性 注意事项 编号(id) long型,标识不同线程 是 不适合用作唯一标识 名称(name) String型,区分不同线程 否 设置名称有助于 ...
- 学习笔记《Java多线程编程实战指南》一
1.1什么是多线程编程 多线程编程就是以线程为基本抽象单位的一种编程范式,和面向对象编程是可以相容的,事实上Java平台中的一个线程就是一个对象.多线程编程不是线程越多越好,就像“和尚挑水”的故事一样 ...
- [Python编程实战] 第一章 python的创建型设计模式1.1抽象工厂模式
注:关乎对象的创建方式的设计模式就是“创建型设计模式”(creational design pattern) 1.1 抽象工厂模式 “抽象工厂模式”(Abstract Factory Pattern) ...
随机推荐
- 【HDOJ】3184 All Can Do
简单数学题. #include <cstdio> #include <cstring> #include <cstdlib> int main() { int t; ...
- 【转】listView中,checkBox的显示和隐藏
原文网址:http://www.cnblogs.com/vicma/p/3460500.html 在listView中,每个item都有一个ChexBox,当显示的时候在listView外面设置一个按 ...
- openstack neutron debugs lists
- 替换IMG
<?php $str = '<img src="http://img01.feiniu.com/images/show/detail/image/20141031/9b3bbc3 ...
- NetAnalyzer笔记 目录
目录 NetAnalyzer笔记 之 一 开篇语 NetAnalyzer笔记 之 二 简单的协议分析 NetAnalyzer笔记 之 三 用C++做一个抓包程序 NetAnalyzer笔记 之 四 C ...
- Eclipse中设置编码的方式
如果要使插件开发应用能有更好的国际化支持,能够最大程度的支持中文输出,则最好使 Java文件使用UTF-8编码.然而,Eclipse工 作空间(workspace)的缺省字符编码是操作系统缺省的编码, ...
- android避免decodeResource图片时占用太大的内存
增加largeHeap="true"属性. android:largeHeap Whether your application's processes should be cre ...
- IT English Collection(16) of Message
1 前言 本文介绍了关于Objective-C中的消息机制,详情如下. 转载请注明出处:http://blog.csdn.net/developer_zhang 2 详述 2.1 原文 A messa ...
- [ES6] Module export
Default export: Default export is easy way to export a function to outside module. //flash-message.j ...
- iOS开发之多媒体API
播放视频 视频文件介绍 视频格式可以分为适合本地播放的本地影像视频和适合在网络中播放的网络流媒体影像视频两大类.尽管后者在播放的稳定性和播放画面质量上可能没有前者 优秀,但网络流媒体影像视频的广泛传播 ...