案例学习

# 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的更多相关文章

  1. 03python面向对象编程5

    5.1 继承机制及其使用 继承是面向对象的三大特征之一,也是实现软件复用的重要手段.Python 的继承是多继承机制,即一个子类可以同时有多个直接父类. Python 子类继承父类的语法是在定义子类时 ...

  2. 03python面向对象编程4

    http://c.biancheng.net/view/2287.html 1.1定义类和对象 在面向对象的程序设计过程中有两个重要概念:类(class)和对象(object,也被称为实例,insta ...

  3. 03python面向对象编程2

    3.继承 如果你要编写的类是另一个现成类的特殊版本,可使用继承.一个类继承另一个类时,它将自动获得另一个类的所有属性和方法:原有的类称为父类,而新类称为子类.子类继承了其父类的所有属性和方法,同时还可 ...

  4. 03python面向对象编程1

    1.创建和使用类 1.1 创建 Dog 类.根据 Dog 类创建的每个实例都将存储名字和年龄.我们赋予了每条小狗蹲下( sit() )和打滚( roll_over() )的能力: In [2]: cl ...

  5. angular2系列教程(六)两种pipe:函数式编程与面向对象编程

    今天,我们要讲的是angualr2的pipe这个知识点. 例子

  6. 带你一分钟理解闭包--js面向对象编程

    上一篇<简单粗暴地理解js原型链--js面向对象编程>没想到能攒到这么多赞,实属意外.分享是个好事情,尤其是分享自己的学习感悟.所以网上关于原型链.闭包.作用域等文章多如牛毛,很多文章写得 ...

  7. PHP 面向对象编程和设计模式 (1/5) - 抽象类、对象接口、instanceof 和契约式编程

    PHP高级程序设计 学习笔记 2014.06.09 什么是面向对象编程 面向对象编程(Object Oriented Programming,OOP)是一种计算机编程架构.OOP 的一条基本原则是计算 ...

  8. Delphi_09_Delphi_Object_Pascal_面向对象编程

    今天这里讨论一下Delphi中的面向对象编程,这里不做过多过细的讨论,主要做提纲挈领的描述,帮助自己抓做重点. 本随笔分为两部分: 一.面向对象编程 二.面向对象编程详细描述 ------------ ...

  9. python基础-面向对象编程

    一.三大编程范式 编程范式即编程的方法论,标识一种编程风格 三大编程范式: 1.面向过程编程 2.函数式编程 3.面向对象编程 二.编程进化论 1.编程最开始就是无组织无结构,从简单控制流中按步写指令 ...

随机推荐

  1. 异步分发任务celery

    Celery简介 Celery是一个功能完备即插即用的任务队列.它使得我们不需要考虑复杂的问题,使用非常简单. celery适用异步处理问题,当遇到发送邮件.或者文件上传, 图像处理等等一些比较耗时的 ...

  2. Vue知识整理16:单文件组件

    过程较为复杂,这里直接写出视频地址,可以直接查看 https://learning.dcloud.io/#/?vid=14

  3. C 语言结构体 struct 及内存对齐

    struct 结构体 对于复杂的数据类型(例如学生.汽车等),C 语言允许我们将多种数据封装到一起,构成新类型. 跟面向对象语言中的对象相比,结构体只能包含成员变量,不支持操作. #include & ...

  4. Django 实现分库

    网站后端的数据库随着业务的不断扩大,用户的累积,数据库的压力会逐渐增大.一种办法是优化使用方法,也就是的优化 SQL 语句啦,添加缓存以达到减少存取的目的:另外一种办法是修改使用架构,在数据库层面上「 ...

  5. 【FICO系列】SAP FICO FS00修改科目为未清项目管理

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[FICO系列]SAP FICO FS00修改科 ...

  6. note.js使用express创建项目的步骤以及ip和端口配置

    1.安装express npm install -g express 2.创建项目 express -e 项目名称 3.打开cmd进入项目目录安装依赖 npm install 4.打开配置文件./bi ...

  7. 【Qt开发】设置Qt应用程序图标

    [Qt开发]设置Qt应用程序图标 标签:[Qt开发] 首先,准备一个图标,例如:zx.ico,并新建一个文本文档,在里面添加一行: IDI_ICON1 ICON DISCARDABLE"zx ...

  8. 20191127 Spring Boot官方文档学习(5)

    5.Spring Boot Actuator:可投入生产的功能 Spring Boot包含许多其他功能,可帮助您在将应用程序投入生产时监控和管理您的应用程序.您可以选择使用HTTP端点或JMX管理和监 ...

  9. ELK7.4.0分析nginx json日志

    ELK7.4.0单节点部署 环境准备 安装系统,数据盘设置为/srv 内核优化参考 我们需要创建elk专用的账号,并创建所需要的目录并授权 useradd elk; mkdir /srv/{app,d ...

  10. 实用网站推荐——office模板(PPT)

    今天给大家分享一批Office的模板网站! office模板比较多的是PPT模板,做PPT是一件非常痛苦的事,自己做的要么太丑,要么搭配太单一,所以今天给大家分享一批网站,再也不用愁做PPT了. wo ...