Python面向对象基础示例_创建对象
生活随笔
收集整理的這篇文章主要介紹了
Python面向对象基础示例_创建对象
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Python面向?qū)ο蠡A(chǔ)示例_創(chuàng)建對象
?
python是面向?qū)ο蟮恼Z言,你可以很輕松的創(chuàng)建一個類和對象。本書代碼源自<<Python 3 Object-Oriented Programming>>,通過借助命令行界面構(gòu)建可對筆記就行增、查、改的案例。本文旨在對代碼的解讀,詳見代碼處注釋部分。
notebook.py
import datetime# 保存下一個筆記對象的id last_id = 0class Note:'''該類是筆記本類,它可以按照指定的字符串檢索和保存筆記內(nèi)容'''def __init__(self, memo, tags=""):"""初始化一個含有文本和可選標(biāo)簽的筆記,自動給筆記生成創(chuàng)建時間和id"""# 定義memo筆記內(nèi)容、tags筆記標(biāo)簽、creation_date創(chuàng)建時間、id筆記編號self.memo = memoself.tags = tagsself.creation_date = datetime.date.today()global last_idlast_id += 1self.id = last_iddef match(self, filter):"""判斷給定的字符串是否匹配上文本或者標(biāo)記,是則True反正則反"""# 如果字符串在memo或者tags屬性里則為True否則為Falsereturn filter in self.memo or filter in self.tagsclass Notebook:"""創(chuàng)建一批可以標(biāo)記、修改、檢索的筆記集合"""def __init__(self):"""初始化個含有空的筆記列表的筆記本對象."""# 定義一個屬性為notes的空的列表self.notes = []def new_note(self, memo, tags=""):"""創(chuàng)建個筆記對象并放置到筆記列表中"""# 通過列表的append方法追加Note對象到notes屬性內(nèi)self.notes.append(Note(memo, tags))def _find_note(self, note_id):"""通過指定的筆記id查找筆記"""# 遍歷notes列表,通過有一個筆記的id與參數(shù)的相同則返回一個note對象,否則為Nonefor note in self.notes:if str(note.id) == str(note_id):return notereturn Nonedef modify_memo(self, note_id, memo):"""通過指定的筆記id查找筆記并將其內(nèi)容更改為輸入的字符串."""#通過find_note方法找到筆記,如果存在該對象則將memo屬性設(shè)置為傳入的字符串并范圍True,找不到則為Falsenote = self._find_note(note_id)if note:note.memo = memoreturn Truereturn Falsedef modify_tags(self, note_id, tags):"""F通過指定的筆記id查找筆記并將其標(biāo)簽更改為輸入的字符串."""note = self._find_note(note_id)if note:note.tags = tagsreturn Truereturn Falsedef search(self, filter):"""找到所有匹配到文本和標(biāo)記的筆記"""# 遍歷notes列表如果通過輸入字符串匹配文本內(nèi)容和標(biāo)簽則返回該筆記對象,否則為Nonereturn [note for note in self.notes if note.match(filter)]'''for note in self.notes:if note.match(filter):return noteelse:return None'''menu.py
import sys import os from notebook import Notebooksys.path.append(os.getcwd()) class Menu:"""顯示菜單說明并執(zhí)行用戶指定的選項"""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 Menu1. Show all Notes 2. Search Notes 3. Add Note 4. Modify Note 5. Quit """)def run(self):"""根據(jù)用戶的選擇執(zhí)行對應(yīng)的動作."""while True:self.display_menu()choice = input("Enter an option: ")#通過choices字段映射到相應(yīng)的操作action = self.choices.get(choice)#print(action.__name__)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.notesfor 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: ")tag = input("Enter a tag: ")self.notebook.new_note(memo,tag)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() # python命令里顯示代碼處的函數(shù)注釋 E:\noteprac>python -i notebook.py >>> help(Note)?查看代碼注釋效果:
Help on class Note in module __main__:class Note(builtins.object)| Note(memo, tags='')|| 該類是筆記本類,它可以按照指定的字符串檢索和保存筆記內(nèi)容|| Methods defined here:|| __init__(self, memo, tags='')| 初始化一個含有文本和可選標(biāo)簽的筆記,自動給筆記生成創(chuàng)建 時間和id|| match(self, filter)| 判斷給定的字符串是否匹配上文本或者標(biāo)記,是則True反正則 反|| ----------------------------------------------------- ------------| Data descriptors defined here:|| __dict__| dictionary for instance variables (if defined)|| __weakref__| list of weak references to the object (if defined?
總結(jié)
以上是生活随笔為你收集整理的Python面向对象基础示例_创建对象的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: A-10攻击机为什么被一些人叫飞行坦克
- 下一篇: Python面向对象简单继承