【发布时间】:2019-03-02 11:55:35
【问题描述】:
我是一名自学成才的程序员,在 python 中的 @decorator 方面需要您的帮助。
这是我的问题。在我用装饰器运行 other(multiply) 之后,它出现了一个错误: wrap_func() 接受 0 个位置参数,但给出了 1 个。我不知道为什么以及如何解决这个问题。 我的主要目的是学习装饰器是如何工作的;因此下面的代码可能没有意义。
def multiply(a,b):
return a*b
###pass in multiply function in other()
def other(multiply):
print('passed in')
print(multiply(1,2))
other(multiply)
### result shows passed in and 2, as expected
### Set up decorator func here
def decorator_prac(old_func):
def wrap_func():
multiply(1,2)
old_func()
print(1+7)
return wrap_func
###add decorator on def other(multiply)
@decorator_prac
def other(multiply):
print('what should I say')
print(multiply(1,2))
###Run other(multiply)
other(multiply)
输出:
passed in
2
Traceback (most recent call last):
File "so.py", line 28, in <module>
other(multiply)
TypeError: wrap_func() takes 0 positional arguments but 1 was given
【问题讨论】:
-
欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。您发布的内容因各种缩进错误而死,也许还有其他问题。
-
我想我修正了缩进...我更新了你的帖子,现在我的输出与你的解释和 cmets 兼容。请验证。
-
@Prune,谢谢....没有意识到缩进。我的坏
-
@Prune,但我该如何解决这个错误?