解释器中的Python装饰器[重复]

问题描述 投票:0回答:1

如何在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
>>>
python decorator python-decorators
1个回答
4
投票

您正在尝试装饰一个表达式;你忘记使用

def
,在一种情况下,你甚至缩进
hello()
行。 Python 文件中的相同代码将失败并出现相同的错误,这里的交互式解释器和 Python 源文件之间没有区别。

装饰器只作用于类和函数;如果您实际上尝试将其与函数定义语句一起使用,它会很好地工作:

>>> def foo(f):
...     return f
... 
>>> @foo
... def bar():
...     pass
... 

如果您想将其应用到现有函数,您需要使用:

>>> hello = makebold(hello)

因为这正是

@expression
语法最终要做的事情。

© www.soinside.com 2019 - 2024. All rights reserved.