@修饰符:在模块或者类里面修饰函数或者方法。。

只可以在模块或类定义层内对函数进行修饰,不允许修修饰一个类。 一个修饰符就是一个函数,它将被修饰的函数做为参数,并返回修饰后的同名函数或其它可调用的东西。例子:
def s(fn):
def saygood(*args):
print "Good"*3
return fn(*args)
return saygood

@s
def u(a, b):
print a**2+b**2

if __name__ == "__main__":
u(3, 4)
u(3, 5)

程序运行结果:
GoodGoodGood
25
GoodGoodGood
34

若把return fn(*args)注释掉,结果是:
GoodGoodGood
GoodGoodGood
要想使u函数能正常运行,必须加返回值,@s是一个statement,会将u函数当作参数传入来执行saygood方法

相关文章:

  • 2022-02-13
  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2022-12-23
  • 2021-07-04
猜你喜欢
  • 2021-06-10
  • 2022-12-23
  • 2019-07-17
  • 2021-06-22
  • 2022-02-14
  • 2022-12-23
相关资源
相似解决方案