python 装饰器

2020-10-20  本文已影响0人  hehehehe

装饰器的作用: 在不改变原有功能代码的基础上,添加额外的功能,如用户验证等。
@wraps(view_func)的作用: 不改变使用装饰器原有函数的结构(如name, doc)

def say_hello(contry):
  def wrapper(func):
    def deco(*args, **kwargs):
      if contry == "china":
        print("你好!")
      elif contry == "america":
        print('hello.')
      else:
        return

      # 真正执行函数的地方
      func(*args, **kwargs)
    return deco
  return wrapper

@say_hello("china")
def chinese():
  print("我来自中国。")

@say_hello("america")
def american():
  print("I am from America.")


if __name__ == '__main__':
  american()
  print("------------")
  chinese()

  print("============")

  say_hello("hello")(american())
  say_hello("hello")(chinese())


hello.
I am from America.
------------
你好!
我来自中国。
============
hello.
I am from America.
你好!
我来自中国。
[Finished in 0.3s]

def say_hello(contry):
  print(1)
  def wrapper(func):
    print(2)
    def deco(*args, **kwargs):
      print(3)
      if contry == "china":
        print("你好!")
      elif contry == "america":
        print('hello.')
      else:
        return

      # 真正执行函数的地方
      func(*args, **kwargs)
    return deco
  return wrapper

@say_hello("china")
def chinese():
  print("我来自中国。")

@say_hello("america")
def american():
  print("I am from America.")




if __name__ == '__main__':
  american()
  print("------------")
  chinese()

  # print("============")

  # say_hello("hello")(american())
  # say_hello("hello")(chinese())


1
2
1
2
3
hello.
I am from America.
------------
3
你好!
我来自中国。
[Finished in 0.9s]
上一篇 下一篇

猜你喜欢

热点阅读