python中'@'符号用作函数修饰符

    '@'符号用作函数修饰符是python2.4新增加的功能,修饰符必须出现在函数定义前一行,不允许和函数定义在同一行。也就是说 @A def f(): 是非法的。 只可以在模块或类定义层内对函数进行修饰,不允许修修饰一个类。 一个修饰符就是一个函数,它将被修饰的函数做为参数,并返回修饰后的同名函数或其它可调用的东西。
    请看以下实例:

    >>> def spamrun(fn):
    ...     def sayspam(*args):
    ...         print "spam, spam, spam"
    ...     return sayspam
    ...
    >>> @spamrun
    ... def useful(a, b):
    ...     print a**2 + b**2
    ...
    >>> useful(3,4)
    spam, spam, spam

请参考python主页中的文档:http://www.python.org/dev/peps/pep-0318/,相信会对修饰符有一个更深入的认识。

更多例子:
Listing 1. Bad decorator that does not even return function


            
>>> def spamdef(fn):
...     print "spam, spam, spam"
...
>>> @spamdef
... def useful(a, b):
...     print a**2 + b**2
...
spam, spam, spam
>>> useful(3, 4)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'NoneType' object is not callable


 

A decorator might return a function, but one that is not meaningfully associated with the undecorated function:


Listing 2. Decorator whose function ignores passed-in function

        
>>> def spamrun(fn):
...     def sayspam(*args):
...         print "spam, spam, spam"
...     return sayspam
...
>>> @spamrun
... def useful(a, b):
...     print a**2 + b**2
...
>>> useful(3,4)
spam, spam, spam

 

Finally, a better behaved decorator will in some way enhance or modify the action of the undecorated function:


Listing 3. Decorator that modifies behavior of undecorated func

        
>>> def addspam(fn):
...     def new(*args):
...         print "spam, spam, spam"
...         return fn(*args)
...     return new
...
>>> @addspam
... def useful(a, b):
...     print a**2 + b**2
...
>>> useful(3,4)
spam, spam, spam

25

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值