亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python3 包裝函數

Python3 包裝函數

躍然一笑 2023-07-05 16:38:19
我在任何地方都找不到問題的解決方案,所以也許我可以在這里得到答案。基本上,我嘗試用另一個函數打印一個元組,然后嘗試將該輸出包裝在另一個函數中。如果我將文本包裝在wrapped_string_linesplit()函數中,它可以完美工作,但我基本上不希望這樣。也許有人可以解釋我的錯誤在哪里,以及從另一個函數包裝它的一個好的解決方案是什么。提前致謝工作解決方案:def wrapped_string_linesplit(arg):    print('#' * 30)    for item in arg:        print(item)    print('#' * 30)def welcome_message():    first = 'Welcome to xyz'.center(30, ' ')    second = ('#' * 30).center(30, ' ')    third = 'New Game'.center(30, ' ')    fourth = 'Load Game'.center(30, ' ')    fifth = 'About'.center(30, ' ')    sixth = 'Quit Game'.center(30, ' ')    return first, second, third, fourth, fifth, sixthwrapped_string_linesplit(welcome_message())輸出:##############################        Welcome to xyz        ##############################           New Game                     Load Game                       About                       Quit Game           ##############################然后將代碼更改為以下內容,根本不會打印換行而不會出現錯誤:def message_wrapper(foo):    def wrap():        print('#' * 30)        foo()        print('#' * 30)    return wrap    def string_linesplit(arg):    for item in arg:        print(item)message_wrapper(string_linesplit(welcome_message()))輸出:        Welcome to xyz##############################           New Game                     Load Game                       About                       Quit Game           ##############################下一個我完全不明白,這個拋出錯誤foo()TypeError:在 message_wrapper() 內調用 foo() 時,“NoneType”對象不可調用。為什么它必須有一個返回值才能從另一個函數調用?def message_wrapper(foo):    print('#' * 30)    foo()    print('#' * 30)def string_linesplit(arg):    for item in arg:        print(item)message_wrapper(string_linesplit(welcome_message()))
查看完整描述

1 回答

?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

我對給定的代碼片段感到困惑,但是如果我必須處理給定的代碼片段并給出如上所述的輸出:


def welcome_message():

    first = 'Welcome to xyz'.center(30, ' ')

    second = ('#' * 30).center(30, ' ')

    third = 'New Game'.center(30, ' ')

    fourth = 'Load Game'.center(30, ' ')

    fifth = 'About'.center(30, ' ')

    sixth = 'Quit Game'.center(30, ' ')

    return first, second, third, fourth, fifth, sixth



def string_linesplit(arg):

    for item in arg:

        print(item)


def message_wrapper(foo):

    print('#' * 30)

    string_linesplit(foo())

    print('#' * 30)


message_wrapper(welcome_message)

輸出:


##############################

        Welcome to xyz        

##############################

           New Game           

          Load Game           

            About             

          Quit Game           

##############################


查看完整回答
反對 回復 2023-07-05
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號