开始慢慢学习这本书了。。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) ...
随机推荐
- 如何消除word中的回车符号
打开文字编辑页面,在菜单栏上选择工具-选项-视图-格式标志中的“段落标志”复选框前面的“√”去掉即可. 附件:
- 华夏的理财30天A和华夏财富宝货币哪个收益比较好?
1.收益性比较 华夏理财30天A001057属于债券型基金,华夏财富宝货币000343属于货币型基金(活期宝,类似余额宝)收益不同 2.流动性 活期宝是可以随时取现的产品,30天A是有封闭期的产品,这 ...
- android调用系统自带的的浏览器搜索关键字
//调用系统的浏览器搜索详情 public void jumpBrowser(String value) { /* 取得网页搜寻的intent */ Intent search = new Inten ...
- CF- Day at the Beach
C. Day at the Beach time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- jdk各个版本的特性
http://blog.csdn.net/mixiuali/article/details/8180100
- HTML5迷你游戏作验证码
验证码最常见的是各种变形的字符,因为识别程序进化得越来越聪明,验证码也变得越来越难以识别,给用户造成了很多的麻烦和反感. 已经有很多人尝试过各种改进的验证码,比如动画的验证码,做题目的验证码,要回答问 ...
- WingIDE注册破解方法
WingIDE是Python程序语言设计的集成开发环境,具有语法标签高亮显示,命令自动完成和函数跳转列表等非常强大的功能.本文主要介绍WingIDE 5安装及注册破解方法. 1. WingIDE 5下 ...
- Python Cookbook笔记
字符串:s.strip() 删除字符串开始和结尾的空白字符. s.lstrip() 删除左边的,s.rstrip() 删除右边的. 随机数:random.random() 生成0-1之间的数. ...
- 共享IP云主机(VPS)玩转wdcp
目前国内有不少性能还不错的共享IP VPS,但因为没有独立IP,所以环境配置起来会比较麻烦. 因为本人自己现在用的就是共享IP的vps,所以把一些配置方法分享一下,供大家参考. 首先是系统的选择,根据 ...
- Android中设置文本颜色的三种方法
最近刚开始学web,发现好的颜色搭配可以让自己的网页更加美观, 中午不想做事,就无聊滴花了两个小时测试了所有颜色的编码,总结如下 新手没有什么吊炸天的技术,仅仅是一份辅助的文档,有兴趣的朋友可以收藏下 ...