如何在Python交互式shell(解释器)中使用此代码:
@makebold
@makeitalic
def hello():
print ("Hello, world!")
在 shell 中我收到此错误:
>>> @makebold
... hello()
File "<stdin>", line 2
hello()
^
IndentationError: unexpected indent
>>> @makebold
... hello()
File "<stdin>", line 2
hello()
^
SyntaxError: invalid syntax
>>>
您正在尝试装饰一个表达式;你忘记使用
def
,在一种情况下,你甚至缩进 hello()
行。 Python 文件中的相同代码将失败并出现相同的错误,这里的交互式解释器和 Python 源文件之间没有区别。
装饰器只作用于类和函数;如果您实际上尝试将其与函数定义语句一起使用,它会很好地工作:
>>> def foo(f):
... return f
...
>>> @foo
... def bar():
... pass
...
如果您想将其应用到现有函数,您需要使用:
>>> hello = makebold(hello)
因为这正是
@expression
语法最终要做的事情。