如何解决Python3包装函数
我在任何地方都找不到解决问题的方法,所以也许我可以在这里找到答案。 基本上,我尝试使用另一个函数打印一个元组,然后尝试将该输出包装到另一个函数中。如果我将文本包装在wrapd_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,sixth
wrapped_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:“ nonetype”对象不可调用 在message_wrapper()中调用foo()时。 为什么它必须具有返回值才能从另一个函数调用?
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()))
解决方法
我对给定的代码段感到困惑,但是如果我必须处理给定的代码段并如上所述给出输出,则为:
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
##############################
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。