美文网首页
python 装饰器

python 装饰器

作者: hehehehe | 来源:发表于2020-10-20 11:02 被阅读0次

装饰器的作用: 在不改变原有功能代码的基础上,添加额外的功能,如用户验证等。
@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]

相关文章

  • 装饰器模式

    介绍 在python装饰器学习 这篇文章中,介绍了python 中的装饰器,python内置了对装饰器的支持。面向...

  • python中的装饰器

    python装饰器详解 Python装饰器学习(九步入门) 装饰器(decorator) 就是一个包装机(wrap...

  • [译] Python装饰器Part II:装饰器参数

    这是Python装饰器讲解的第二部分,上一篇:Python装饰器Part I:装饰器简介 回顾:不带参数的装饰器 ...

  • Python中的装饰器

    Python中的装饰器 不带参数的装饰器 带参数的装饰器 类装饰器 functools.wraps 使用装饰器极大...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • Python 装饰器填坑指南 | 最常见的报错信息、原因和解决方

    Python 装饰器简介装饰器(Decorator)是 Python 非常实用的一个语法糖功能。装饰器本质是一种返...

  • Python装饰器

    Python装饰器 一、函数装饰器 1.无参装饰器 示例:日志记录装饰器 2.带参装饰器 示例: 二、类装饰器 示例:

  • python3基础---详解装饰器

    1、装饰器原理 2、装饰器语法 3、装饰器执行的时间 装饰器在Python解释器执行的时候,就会进行自动装饰,并不...

  • 2019-05-26python装饰器到底是什么?

    装饰器例子 参考语法 装饰器是什么?个人理解,装饰器,是python中一种写法的定义。他仍然符合python的基本...

  • 2018-07-18

    Python装饰器 装饰,顾名思义,是用来打扮什么东西的。Python装饰...

网友评论

      本文标题:python 装饰器

      本文链接:https://www.haomeiwen.com/subject/haarmktx.html