第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Python 中的狀態(tài)模式

Python 中的狀態(tài)模式

慕無(wú)忌1623718 2021-09-11 16:04:45
我在用 Python 實(shí)現(xiàn)狀態(tài)設(shè)計(jì)模式時(shí)遇到了一些問題。我是 Python 的新手,并編寫了一些代碼來(lái)嘗試回答提出給我的這個(gè)問題:為一個(gè)簡(jiǎn)單的 ATM 編寫代碼,允許用戶插入他們的卡、輸入他們的 PIN、請(qǐng)求現(xiàn)金和彈出卡。將以下對(duì)象模型用于顯示狀態(tài)模式使用的系統(tǒng)。您需要確定每個(gè)操作要更改為什么狀態(tài)。請(qǐng)參閱下面的 UML 圖以獲取更多信息:下面是我的嘗試...import reclass AtmState(object):    name = "ready"    allowed = []    def switch(self, state):        """ Switch to new state """        if state.name in self.allowed:#             print("Current {} => switched to new state {}.".format(self, state.name))            self.__class__=state# These print statements show how you switch between states.#         else:#             print("Current {} => switched to {} not possible.".format(self, state.name))    def getState(self):        print("The current state is {}".format(self.state))    def __str__(self):        return self.name    def __repr__(self):        return r"The ATM is in a {} state.".format(self.state)    def insertCard(self, card):        # Set messages for card format and inserted        wrong_format = "Please insert your card in the following format: XXXX-XXXX-XXXX-XXXX."        card_inserted = "Card Inserted: {}"        card_pattern='^([0-9]{4})(-?|\s)([0-9]{4})(-?|\s)([0-9]{4})(-?|\s)([0-9]{4})$'        pattern = re.compile(card_pattern)        if pattern.match(card) and str(self.state) in ["insert", "ready", "no card"]:            self.state.switch(HasCard)            print(card_inserted.format(card))            self.state.switch(HasPin)        elif pattern.match(card)==False and str(self.state) ["insert", "ready", "no card"]:            print(wrong_format)        elif str(self.state) in ["enter_pin", "withdraw"]:            print("Card already inserted")        elif str(self.state) in ["no card"]:            print("Error: No Card Inserted. Please insert card.")對(duì)我來(lái)說最大的困惑是如何使用類來(lái)實(shí)現(xiàn)它?我能夠獲得正確的邏輯,但我正在努力使用狀態(tài)設(shè)計(jì)模式進(jìn)行實(shí)現(xiàn)。任何指導(dǎo)將不勝感激。
查看完整描述

2 回答

?
嚕嚕噠

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊

這是您問題的簡(jiǎn)化版本的python3中的快速而骯臟的實(shí)現(xiàn)。


State 是一個(gè)抽象類,使用(Mickeal 描述的 abc 包)充當(dāng)接口(派生類必須實(shí)現(xiàn)抽象方法)。實(shí)際狀態(tài)接收請(qǐng)求并實(shí)現(xiàn)函數(shù)并執(zhí)行狀態(tài)轉(zhuǎn)換這就是為什么我將 atm 對(duì)象作為參數(shù)方法傳遞


import abc

class State(object,metaclass = abc.ABCMeta):

    @abc.abstractmethod

    def eject(self, atm):

        raise NotImplementedError('')

    @abc.abstractmethod

    def insert(self, atm):

        raise NotImplementedError('')



class NoCard(State):

    def eject(self, atm):

        print('Error : no card')

    def insert(self, atm):

        print('ok')

        atm.state  = HasCard()


class HasCard(State):

    def eject(self, atm):

        print('ok')

        atm.state = NoCard()

    def insert(self, atm):

        print('Error : card already present')



class ATM:

    def __init__(self):

        self.state = NoCard()

    def insert(self):

        self.state.insert(self)

    def eject(self):

        self.state.eject(self)


if __name__ == "__main__":

    atm = ATM()

    atm.eject() # default state is no card error no card

    atm.insert() # ok state is has card

    atm.insert() # error  card already in

    atm.eject() # ok  state become no card

    atm.eject() # error no card



查看完整回答
反對(duì) 回復(fù) 2021-09-11
?
ITMISS

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊

Atm不應(yīng)該從AtmState但從無(wú)(或從object,無(wú)所謂)繼承。它應(yīng)該只包含:state變量、change改變狀態(tài)AtmState的方法以及調(diào)用當(dāng)前同名方法的方法中的每個(gè)方法,并state帶有一個(gè)名為例如atm包含調(diào)用Atm對(duì)象(上下文)的附加參數(shù)。

AtmState應(yīng)該只包含沒有實(shí)現(xiàn)的方法(并且沒有變量),因?yàn)樗窃寄J街械慕涌?。?duì)于 Python,您應(yīng)該使其成為具有抽象方法的抽象類,請(qǐng)參閱模塊abc如何做到這一點(diǎn)。

派生自的具體類AtmState現(xiàn)在應(yīng)該實(shí)現(xiàn)這些方法。通常每個(gè)類只需要一兩個(gè)方法,其余的應(yīng)該只打印一個(gè)錯(cuò)誤。例如,該NoCard.ejectCard()方法僅顯示無(wú)法彈出不存在的卡的錯(cuò)誤。

通過從方法之一調(diào)用atm.change()方法(atm是由Atm類添加的附加參數(shù)),可以在狀態(tài)之間切換。


查看完整回答
反對(duì) 回復(fù) 2021-09-11
  • 2 回答
  • 0 關(guān)注
  • 253 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)