03python面向对象编程3
案例学习





# notebook.py
import datetime # Store the next available id for all new notes
last_id = 0 class Note:
"""Represent a note in the notebook. Match against a
string in searches and store tags for each note.""" def __init__(self, memo, tags=""):
"""initialize a note with memo and optional
space-separated tags. Automatically set the note's
creation date and a unique id."""
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
global last_id
last_id += 1
self.id = last_id def match(self, filter):
"""Determine if this note matches the filter
text. Return True if it matches, False otherwise. Search is case sensitive and matches both text and
tags."""
return filter in self.memo or filter in self.tags
对以上模块进行测试:

In [1]: from notebook import Note
In [2]: n1 = Note("hello first")
In [3]: n2 = Note("hello again")
In [4]: n1.id
Out[4]: 1
In [5]: n2.id
Out[5]: 2
In [6]: n1.match('hello')
Out[6]: True
In [7]: n2.match('second')
Out[7]: False
接下来创建我们的笔记本:
# notebook.py
class Notebook:
"""Represent a collection of notes that can be tagged,
modified, and searched.""" def __init__(self):
"""Initialize a notebook with an empty list."""
self.notes = [] def new_note(self, memo, tags=""):
"""Create a new note and add it to the list."""
self.notes.append(Note(memo, tags)) def _find_note(self, note_id):
"""Locate the note with the given id."""
for note in self.notes:
if str(note.id) == str(note_id):
return note
return None def modify_memo(self, note_id, memo):
"""Find the note with the given id and change its
memo to the given value."""
note = self._find_note(note_id)
if note:
note.memo = memo
return True
return False def modify_tags(self, note_id, tags):
"""Find the note with the given id and change its
tags to the given value."""
note = self._find_note(note_id)
if note:
note.tags = tags
return True
return False def search(self, filter):
"""Find all notes that match the given filter
string."""
return [note for note in self.notes if note.match(filter)]
检测:

In [1]: from notebook import Note,Notebook
In [2]: n = Notebook()
In [3]: n.new_note('hello world')
In [4]: n.new_note('hello again')
In [5]: n.notes
Out[5]: [<notebook.Note at 0x4be87f0>, <notebook.Note at 0x4bc3358>]
In [6]: n.notes[0].id
Out[6]: 1
In [7]: n.notes[1].id
Out[7]: 2
In [8]: n.notes[0].memo
Out[8]: 'hello world'
In [9]: n.notes[1].memo
Out[9]: 'hello again'
In [10]: n.search('hello')
Out[10]: [<notebook.Note at 0x4be87f0>, <notebook.Note at 0x4bc3358>]
In [11]: n.search('world')
Out[11]: [<notebook.Note at 0x4be87f0>]
In [12]: n.modify_memo(1,'hi world')
Out[12]: True
接下来是实现菜单接口,接口只需要简单的提供一个菜单,并允许用户输入他们的选择:
import sys
from notebook import Notebook class Menu:
"""Display a menu and respond to choices when run.""" def __init__(self):
self.notebook = Notebook()
self.choices = {
"": self.show_notes,
"": self.search_notes,
"": self.add_note,
"": self.modify_note,
"": self.quit,
} def display_menu(self):
print("""
Notebook Menu 1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
""") def run(self):
"""Display the menu and respond to choices."""
while True:
self.display_menu()
choice = input("Enter an option: ")
action = self.choices.get(choice)
if action:
action()
else:
print("{0} is not a valid choice".format(choice)) def show_notes(self, notes=None):
if not notes:
notes = self.notebook.notes
for note in notes:
print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo)) def search_notes(self):
filter = input("Search for: ")
notes = self.notebook.search(filter)
self.show_notes(notes) def add_note(self):
memo = input("Enter a memo: ")
self.notebook.new_note(memo)
print("Your note has been added.") def modify_note(self):
id = input("Enter a note id: ")
memo = input("Enter a memo: ")
tags = input("Enter tags: ")
if memo:
self.notebook.modify_memo(id, memo)
if tags:
self.notebook.modify_tags(id, tags) def quit(self):
print("Thank you for using your notebook today.")
sys.exit(0) if __name__ == "__main__":
Menu().run()


Notebook Menu 1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit Enter an option: 1 Notebook Menu 1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit Enter an option: 3
Enter a memo: 'nihao'
Your note has been added. Notebook Menu 1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit Enter an option: 1
1:
'nihao' Notebook Menu 1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit Enter an option: 4
Enter a note id: 1
Enter a memo: 'wohao'
Enter tags: 'ok' Notebook Menu 1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit Enter an option: 1
1: 'ok'
'wohao' Notebook Menu 1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit Enter an option: 5
Thank you for using your notebook today.
03python面向对象编程3的更多相关文章
- 03python面向对象编程5
5.1 继承机制及其使用 继承是面向对象的三大特征之一,也是实现软件复用的重要手段.Python 的继承是多继承机制,即一个子类可以同时有多个直接父类. Python 子类继承父类的语法是在定义子类时 ...
- 03python面向对象编程4
http://c.biancheng.net/view/2287.html 1.1定义类和对象 在面向对象的程序设计过程中有两个重要概念:类(class)和对象(object,也被称为实例,insta ...
- 03python面向对象编程2
3.继承 如果你要编写的类是另一个现成类的特殊版本,可使用继承.一个类继承另一个类时,它将自动获得另一个类的所有属性和方法:原有的类称为父类,而新类称为子类.子类继承了其父类的所有属性和方法,同时还可 ...
- 03python面向对象编程1
1.创建和使用类 1.1 创建 Dog 类.根据 Dog 类创建的每个实例都将存储名字和年龄.我们赋予了每条小狗蹲下( sit() )和打滚( roll_over() )的能力: In [2]: cl ...
- angular2系列教程(六)两种pipe:函数式编程与面向对象编程
今天,我们要讲的是angualr2的pipe这个知识点. 例子
- 带你一分钟理解闭包--js面向对象编程
上一篇<简单粗暴地理解js原型链--js面向对象编程>没想到能攒到这么多赞,实属意外.分享是个好事情,尤其是分享自己的学习感悟.所以网上关于原型链.闭包.作用域等文章多如牛毛,很多文章写得 ...
- PHP 面向对象编程和设计模式 (1/5) - 抽象类、对象接口、instanceof 和契约式编程
PHP高级程序设计 学习笔记 2014.06.09 什么是面向对象编程 面向对象编程(Object Oriented Programming,OOP)是一种计算机编程架构.OOP 的一条基本原则是计算 ...
- Delphi_09_Delphi_Object_Pascal_面向对象编程
今天这里讨论一下Delphi中的面向对象编程,这里不做过多过细的讨论,主要做提纲挈领的描述,帮助自己抓做重点. 本随笔分为两部分: 一.面向对象编程 二.面向对象编程详细描述 ------------ ...
- python基础-面向对象编程
一.三大编程范式 编程范式即编程的方法论,标识一种编程风格 三大编程范式: 1.面向过程编程 2.函数式编程 3.面向对象编程 二.编程进化论 1.编程最开始就是无组织无结构,从简单控制流中按步写指令 ...
随机推荐
- leetcode-mid-sorting and searching-162. Find Peak Element
mycode 54.81% class Solution(object): def findPeakElement(self, nums): """ :type num ...
- 博客侧边栏公告html代码
前一小段是时钟: 后一段是百度统计,但是显示不出来. 网站概况 - 百度统计 https://tongji.baidu.com/web/25880379/overview/index 趋势分析 - 百 ...
- day64—ajax技术学习笔记
转行学开发,代码100天——2018-05-19 Ajax技术学习笔记 AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML).AJA ...
- mac 外接显示屏的坑
概述 工作中使用 Mac 外接显示屏,有时会出现闪屏然后黑屏的现象,之前都没有找到原因,今天终于找到了,记录下来,供以后参考,相信对其他人也有用. 参考资料: Macbook外接显示器设置教程 问题 ...
- WPF WebBrowser 加载 html ,出现安全警告, 运行 脚本和 activeX 控件,
对于你的问题,只需要在你的HTML首行添加如下代码即可隐藏安全提示条: <!-- saved from url=(0014)about:internet --> 还有一个可选方案是使用Wi ...
- Jmeter之检查点
检查点 Jmeter中检查点也叫断言,Jmeter中有很多类型的断言,但是最常用的是响应断言,即根据服务器返回的结果来判断测试是否通过. 响应断言 添加断言结果用于运行完毕后查看结果 测试通过 测试不 ...
- delphi xe2 64位嵌入汇编问题 https://bbs.csdn.net/topics/390333981
Function xxx(xxx):xxx;assembler;asm XOR RAX , RAX ...end;这样的可以. 0 0 引用 ・ 举报 ・ 管理 5t4rk 回复于 2013- ...
- FLUME安装&环境(二):拉取MySQL数据库数据到Kafka
Flume安装成功,环境变量配置成功后,开始进行agent配置文件设置. 1.agent配置文件(mysql+flume+Kafka) #利用Flume将MySQL表数据准实时抽取到Kafka a1. ...
- ftp搭建mysql服务器
一.将mysql放入FTP服务器中1.安装FTP yum install -y vsftpd2.准备ftp主目录 mkdir /var/ftp/mysql57/3.官网下载yum仓库的包. ...
- [Web 前端] 030 ajax 是什么
AJAX 是什么 1. AJAX 是一种"艺术" 简单地说 AJAX 是在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的艺术 网上是这样说的 AJAX 指异步 Java ...