使用python中mvc設計模式的介紹

來源:互聯網
上載者:User
一、程式碼群組織(目錄結構)

二、mvc概述

MVC設計模式即MVC架構。

MVC全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫,一種軟體設計典範,用一種商務邏輯和資料顯式分離的方法組織代碼,將商務邏輯被聚集到一個組件裡面,在介面和使用者圍繞資料的互動能被改進和個人化定製的同時而不需要重新編寫商務邏輯。MVC被獨特的發展起來用於映射傳統的輸入、處理和輸出功能在一個邏輯的圖形化使用者介面的結構中。

三、代碼

1、資料

#coding:utf-8 '''類比資料,當然,這是一個元組。也可以是任意的資料庫,只要你喜歡''' Quotes = ('過放蕩不羈的生活,容易得像順水推舟,但是要結識良朋益友,卻難如登天。 —— 巴爾紮克',          '我讀的書愈多,就愈親近世界,愈明了生活的意義,愈覺得生活的重要。 —— 高爾基',          '人生並不像火車要通過每個站似的經過每一個生活階段。人生總是直向前行走,從不留下什麼。 —— 路易斯',          '要永遠覺得祖國的土地是穩固地在你腳下,要與集體一起生活,要記住,是集體教育了你。那一天你若和集體脫離,那便是末路的開始。 —— 奧斯特洛夫斯基',          '在學校和生活中,工作的最重要的動力是工作中的樂趣,是工作獲得結果時的樂趣以及對這個結果的社會價值的認識。 —— 愛因斯坦')

2、模型層
只有模型層才能夠直接存取資料

#_*_coding:utf-8from mvc.database.quote import Quotes #匯入資料  class QuotesModel(object):    '''模型層'''    def get_quote(self,index):        '''根據索引讀取資料        @parameter index 索引值        '''        try:            valve = Quotes[index]        except IndexError as err:            valve = 'Not Found!'        return valve

3、控制器層

#_*_coding:utf-8from mvc.model.quote_model import QuotesModelfrom mvc.view.quoteterminalview import QuoteTerminalView class QuoteterminalController(object):    '''控制器層'''    def __init__(self):        self.model = QuotesModel()        self.view = QuoteTerminalView()     def run(self):        n = self.view.select_quote()        try:            index = int(n)            quote = self.model.get_quote(index)            self.view.show(quote)        except ValueError as err:            self.view.error('不合法的索引值')

4、視圖層

#_*_coding:utf-8 class QuoteTerminalView(object):    '''視圖層'''    def show(self, quote):        '''顯示查詢結果        @parameter quote 接收資料'''        print('您查詢到的名人名言是:%s' % (quote))     def error(self, msg):        '''列印錯誤訊息        @msg msg 接收錯誤訊息'''        print("error: %s" % (msg))     def select_quote(self):        '''讀取使用者的選擇'''        return raw_input("請輸入編號進行查詢:")

5、主程式

#_*_coding:utf-8'''主程式'''from mvc.controller.quoteterminalcontroller import QuoteterminalController def mains():    while True:        controller = QuoteterminalController()        controller.run() if __name__ == '__main__':    mains()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.