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

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

覆蓋在另一個(gè)函數(shù)中進(jìn)行的函數(shù)調(diào)用的參數(shù)

覆蓋在另一個(gè)函數(shù)中進(jìn)行的函數(shù)調(diào)用的參數(shù)

溫溫醬 2022-03-09 20:51:26
說,我有兩個(gè)函數(shù)bar()和foo(). bar()執(zhí)行foo()。def foo():    try:        num = int( input("need an Integer") )    except ValueError:        print("input invalid")def bar():    foo()當(dāng)我運(yùn)行bar()并輸入一個(gè)非整數(shù)值時(shí),我應(yīng)該獲得"input invalid"消息。但是,如果我想"input invalid"在bar() 不修改foo(). 我該怎么辦?我嘗試了以下方法,但這不起作用。def foo():    try:        num = int( input("need an Integer") )    except ValueError:        print("input invalid")def bar():    try:        foo()    except Exception as result:  <-- this does not capture the error in foo()        print("my customized error message")  期望的輸出是:"my customized error message"而不是"input invalid"(但如果我可以輸出兩條消息,這是可以接受的)
查看完整描述

2 回答

?
函數(shù)式編程

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

如果傳入的消息與要替換的消息匹配,您可以使用自定義函數(shù)unittest.mock.patch臨時(shí)覆蓋內(nèi)置print函數(shù),該函數(shù)使用原始函數(shù)打印所需的消息,或者按原樣打印消息:print


from unittest.mock import patch


def custom_print(s, *args, **kwargs):

    orig_print("my customized error message" if s == "input invalid" else s, *args, **kwargs)


orig_print = print


def bar():

    with patch('builtins.print', new=custom_print):

        foo()


bar()


查看完整回答
反對(duì) 回復(fù) 2022-03-09
?
GCT1015

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

你基本上是在一個(gè)很好的方式。你想要做的是raise一個(gè)異常foo,你可以在其中捕獲bar. 這是通過 raise 命令完成的,如下所示:


def foo():

    try:

        num = int( input("need an Integer") )

    except ValueError:

        raise Exception("input invalid")



def bar():

    try:

        foo()


    except Exception as e:

        print("my customized error message")  

如果您現(xiàn)在執(zhí)行bar()并引發(fā)您的異常,您可以捕獲它bar()并打印另一條消息。如果要獲取原始消息,可以通過打印str(e).


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

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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