开始慢慢学习这本书了。。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) ...
随机推荐
- 8.2.1.4 Index Merge Optimization 索引合并优化:
8.2.1.4 Index Merge Optimization 索引合并优化: 索引合并方法是用于检索记录 使用多个 范围扫描和合并它们的结果集到一起 mysql> show index fr ...
- 【HDOJ】4515 小Q系列故事——世界上最遥远的距离
简单题目,先把时间都归到整年,然后再计算.同时为了防止减法出现xx月00日的情况,需要将d先多增加1,再恢复回来. #include <cstdio> #include <cstri ...
- HDU 5505 - BestCoder Round #60 - GT and numbers
题目链接 : http://bestcoder.hdu.edu.cn/contests/contest_chineseproblem.php?cid=641&pid=1002 思路 : N有若 ...
- Palindrome Pairs 解答
Question Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, ...
- Storm实现单词计数
package com.mengyao.storm; import java.io.File; import java.io.IOException; import java.util.Collect ...
- mybatis错误Invalid bound statement (not found) 的解决办法
<!-- IDEA需要添加一下内容,否则无法找到mapper --> <build> <resources> <resource> <direct ...
- Jmeter压力测试环境准备
Jmeter性能监控 配置好测试机器上的jmeter环境:http://jmeter-plugins.org/downloads/all/ 网站下载两个东西: JMeterPlugins-Standa ...
- android实现文本复制到剪切板功能(ClipboardManager)
Android也有剪切板(ClipboardManager),可以复制一些有用的文本到剪贴板,以便用户可以粘贴的地方使用,下面是使用方法 注意:导包的时候 API 11之前: android.te ...
- 新建cocos2d-xproject
在cocos2d-x v3.1.1版本号中,採用命令行的方式来创建一个新的project.比方新建一个名为MyGame的project能够用以下的命令: watermark/2/text/aHR ...
- Redis源代码分析-内存数据结构intset
这次研究了一下intset.研究的过程中,一度看不下过去,可是还是咬牙挺过来了.看懂了也就是那么回事.静下心来,切莫浮躁 Redis为了追求高效,在存储下做了非常多的优化,像intset就是作者为了节 ...