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.编程最开始就是无组织无结构,从简单控制流中按步写指令 ...
随机推荐
- 不能访问windows installer服务
xp系统安装msi类型的安装程序出现以下错误: 不能访问windows installer服务. 解决办法 1:运行cmd -> regsvr32 msi.dll 运行services.msc- ...
- 下载vuejs,Hello Vue(vscode)
下载vuejs,Hello Vue(vscode) Hello Vue 下载使用vue.js 动图演示 Vue的基本使用步骤 传送门:https://cn.vuejs.org/v2/guide/in ...
- Oracle数据库用户的密码过期问题处理
SQL> select username, user_id, account_status,expiry_date, profile from dba_users where username ...
- 我写过的bug...
添加对,更新和查询出错 因为只写了bean里只写了se't方法,没有写get 多条件联合查询,后一个条件没用 写xml里面复制上一行,忘记把变量名改了(propertyValue没改成register ...
- allure2生成html报告
前言 allure是一个report框架,支持java的Junit/testng等框架,当然也可以支持python的pytest框架,也可以集成到Jenkins上展示高大上的报告界面. 环境准备 1. ...
- Flink数据流图的生成----简单执行计划的生成
Flink的数据流图的生成主要分为简单执行计划-->StreamGraph的生成-->JobGraph的生成-->ExecutionGraph的生成-->物理执行图.其中前三个 ...
- Golang http post error : http: ContentLength=355 with Body length 0
参考:https://stackoverflow.com/questions/31337891/net-http-http-contentlength-222-with-body-length-0 问 ...
- python 并发编程 多进程 互斥锁
运行多进程 每个子进程的内存空间是互相隔离的 进程之间数据不能共享的 一 互斥锁 但是进程之间都是运行在一个操作系统上,进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终 ...
- IIS7下配置web.config隐藏index.php
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.we ...
- 蚁群算法解决TSP问题
代码实现 运行结果及参数展示 alpha=1beta=5 rho=0.1 alpha=1beta=1rho=0.1 alpha=0.5beta=1rho=0.1 概念蚁群算法(AG)是一种模拟蚂蚁觅 ...