案例学习

# 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. 读读《编写高质量代码:改善Java程序的151条建议》

    这本书可以作为平时写代码的一个参考书,这本书以我个人读的经验看来,最好是通过平时代码驱动的方式来读,这样吸收的快,也读的快. 这本书主要讲什么,我自己用了个思维导图概述: 根据这种导图可知,主要讲的就 ...

  2. Loading class `com.mysql.jdbc.Driver'. This is deprecated警告处理,jdbc更新处

    1.报错信息是这样的; 处理:提示信息表明数据库驱动com.mysql.jdbc.Driver'已经被弃用了.应当使用新的驱动com.mysql.cj.jdbc.Driver' 所以,按照提示更改jd ...

  3. 阶段3 1.Mybatis_09.Mybatis的多表操作_3 完成account的一对一操作-通过写account的子类方式查询

    先把多表查询的sql语句写出来 想要显示的字段 创建一个AccountUser类 继承Account.这样它就会从父类上继承一些信息 这里只需要定义username和address就可以了 .然后生成 ...

  4. 配置文件pytest.ini

    前言 pytest配置文件可以改变pytest的运行方式,它是一个固定的文件pytest.ini文件,读取配置信息,按指定的方式去运行. ini配置文件 pytest里面有些文件是非test文件 py ...

  5. cmd 中文显示错误,解决办法

    cmd窗口左上角控制按钮(就是图标)上单击-默认-选项-默认编码-936   追问 默认值是936的,但是属性里的当前代码页是437呀,怎么办 囧oz 追答 默认-选项-默认编码-936 不是属性,是 ...

  6. Oracle 无备份情况下的恢复--密码文件/参数文件

    13.1 恢复密码文件 密码文件(linux 为例)在$ORACLE_HOME/dbs目录下,文件名的前缀是orapw,后接数据库实例名. [oracle@DSI backup]$ cd /u01/a ...

  7. css之——div模拟textarea文本域的实现

    1.问题的出现: <textarea>标签为表单元素,但一般用于多行文本的输入,但是有一个明显的缺点就是不能实现高度自适应,内容过多就回出现滚动条. 为了实现高度自适应:用div标签来代模 ...

  8. windows 的cmd设置代理的问题

    今天给公司一同事用cmd来安装gulp(npm install -g gulp), 死活安装不上,一直报一大堆的错误:经仔细查阅是代理的问题,故总结如下: 若公司的电脑是通过设置代理来访问外网,则需要 ...

  9. 记一次Python pip安装失败的总结

    pip 安装失败时,可能换此方法可解决1.升级pip版本,这个一般会主动提示python3 -m pip install --upgrade pip2.修改pip源,默认的pip源速度实在无法忍受,或 ...

  10. springboot(3) 页面到服务器

    第一讲实现了spring boot 环境的下载及配置. 第二讲实现了,从服务器,到页面. 第三讲打算从页面到服务器. 比如,我们希望 从页面,点击一个按钮,传递信息到服务器. 就拿传递用户名和密码来简 ...