案例学习

# 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. [LeetCode]-010-Regular_Expression_Matching

    Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...

  2. tihuantupian

  3. nodejs 文件操作

    前言: nodejs 自带的文件操作的模块  fs 就是对文件的增删查改: 就像我们用的服务器,我们没有办法在运行的文件上进行一直的修改,因为他不向浏览器,刷新后我们的文件会自己修改: 如果想要更改我 ...

  4. 【后台管理系统】—— Ant Design Pro结合插件(一)

    一.富文本braft-editor 安装并引用 npm install braft-editor --save import BraftEditor from 'braft-editor' impor ...

  5. heap和stack区别

    转载自博客:https://www.cnblogs.com/perfy/archive/2012/09/06/2672946.html 1.heap是堆 ,stack是栈 2.stack的空间由操作系 ...

  6. 2018 icpc 青岛

    https://zoj.pintia.cn/contests/91827364639/problems C 要把这两个二进制串变为相同,需要先看哪些位置不同,设为数组c,某位为1则两位不同. 分1形成 ...

  7. Unity3D-Canvas-UIScaleMode

    UnityCanvasUI自适应部分 用Canvas下的自适应UI Scale Mode: Constant Pixel Size:固定像素大小,无论如何UI怎么样就怎么样,只能通过 Scale Fa ...

  8. 中国MOOC_零基础学Java语言_第3周 循环_1奇偶个数

    第3周编程题 查看帮助 返回   第3周编程题 依照学术诚信条款,我保证此作业是本人独立完成的. 温馨提示: 1.本次作业属于Online Judge题目,提交后由系统即时判分. 2.学生可以在作业截 ...

  9. Ubuntu vimrc 和 bashrc 配置

    先上效果图,把vimrc 和bashrc 备份一下.. vimrc: map <F9> :call SaveInputData()<CR> func! SaveInputDat ...

  10. IIS安全狗问题

    1.没有安装以前网站运行正常,安装IIS全狗以后,ajaxpro2出现,找不到任何问题,卸载安全狗以后正常. 2.很久以前遇到的一个问题,有一款NET的cms系统,也是安装了安全狗以后不正常,忘记了c ...