随笔 - 363, 文章 - 0, 评论 - 2, 阅读 - 23万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

03python面向对象编程3

Posted on   心默默言  阅读(217)  评论(0编辑  收藏  举报

案例学习

复制代码
# 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
View Code
复制代码

 接下来创建我们的笔记本:

复制代码
# 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
View Code
复制代码

接下来是实现菜单接口,接口只需要简单的提供一个菜单,并允许用户输入他们的选择:

复制代码
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 = {
            "1": self.show_notes,
            "2": self.search_notes,
            "3": self.add_note,
            "4": self.modify_note,
            "5": 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.
复制代码

 

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示