Python 解释器中的装饰器
如何在Python的交互式命令行(解释器)中使用这段代码:
@makebold
@makeitalic
def hello():
print ("Hello, world!")
在命令行中我遇到了这个错误:
>>> @makebold
... hello()
File "<stdin>", line 2
hello()
^
IndentationError: unexpected indent
>>> @makebold
... hello()
File "<stdin>", line 2
hello()
^
SyntaxError: invalid syntax
>>>
1 个回答
4
你正在尝试给一个表达式加装饰,但你忘记用了def
,而且在某个情况下,你甚至把hello()
这一行缩进了。在Python文件中运行同样的代码也会出现相同的错误,这里交互式解释器和Python源文件没有区别。
装饰器只适用于类和函数;如果你真的尝试在函数定义语句上使用它,那就能正常工作:
>>> def foo(f):
... return f
...
>>> @foo
... def bar():
... pass
...
如果你想把它应用到一个已有的函数上,你需要使用:
>>> hello = makebold(hello)
因为这正是@expression
语法的作用。