[转载]python中的@符号的作用

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

实例(1):

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

 

实例(2):

def spamrun(fn):
        print "spam,spam,spam"

@spamrun
def useful(a,b):
    print a**2+b**2

结果:

spam,spam,spam

 

实例(3):

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

 

实例(4):

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(4,3)

结果:

spam,spam,spam
25


追加

实例

def decorator(fn):
    def test(*args):
        print "My god!"*3
        return fn(*args)
    return test

@decorator
def other(a,b):
    print a**2+b**2

if __name__=="__main__":
    other(4,3)
    other(3,4)
   
结果:

My god!My god!My god!
25
My god!My god!My god!
25
注释掉//print return fn(*args)

结果是:

My god!My god!My god!
My god!My god!My god!

要想使other函数能正常运行,必须加返回值,@decorator是一个statement,会将other函数当作参数传入来执行test方法

posted @   Xander-Hang  阅读(1002)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示