如何解决Python编写Decorators-Str不可调用
我目前正在学习Python,并且已经学习了大约六个月。我已经取得了很大的进步,现在正努力将自己的头缠在装饰工上。我了解装饰器背后的一般概念,并以一种基本格式编写了一些简单的装饰器,但是这次我试图编写一个可以多次使用装饰器的函数:
例如,以下内容:
def make_html(element):
def wrapped(func,*args,**kwargs):
return f'<{element}>' + func(*args,**kwargs) + f'</{element}>'
return wrapped
@make_html('strong')
def get_text(text='I code in Python.'):
return text
print(get_text)
输出以下内容:
<strong>I code in Python.</strong>
但是,如果我在打印时实际上调用了该函数:
print(get_text())
我明白了:
Traceback (most recent call last):
File "AppData/Local/Programs/Python/Python38/search and sort2.py",line 98,in <module>
print(get_text())
TypeError: 'str' object is not callable
类似地,如果我尝试在一个函数上多次使用同一装饰器:
@make_html('p')
@make_html('strong')
def get_text(text='I code in Python.'):
return text
我明白了:
Traceback (most recent call last):
File "AppData/Local/Programs/Python/Python38/search and sort2.py",line 94,in <module>
def get_text(text='I code in Python.'):
File "Local/Programs/Python/Python38/search and sort2.py",line 83,in wrapped
return f'<{element}>' + func(*args,**kwargs) + f'</{element}>'
TypeError: 'str' object is not callable
关于这里出了什么问题的任何想法?如何在一个函数上多次使用同一个装饰器,为什么我的函数被解释为字符串?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。