zoukankan      html  css  js  c++  java
  • 装饰器

    一、装饰器

    1.1、装饰器的作用:

      装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象,它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码并继续重用。简单点说就是:不改变原来函数本身,在函数前面或者后面增加一些额外的功能。

    1.2、关于编码规范

      定义函数的时候当多个单词拼接在一起的时候首个单词的首字母小写第二个单词首字母要大写,而类则是每个单词的首个字母大写

    1.3、理解装饰器

    def hello():
    print("hello world")

    a = hello()
    b = hello

    # a 代表hello函数把返回这给到a
    # b 代表的是一个函数, b()相当于hello()
    装饰器示例:
    def startEnd(func):
    def start():
    print("######start######")
    func()
    print("#######end#######")
    return start

    @startEnd
    def hello():
    print("hello world")
    hello()

    ①、装饰器使用@符号进行使用,相当于把hello() 函数作为参数,传给startEnd()
    ②、@startEnd 相当于 hello = startEnd(hello)
    ③、当调用hello()的时候,就相当于调用了startEnd(hello())()

       带参数的装饰器:

    def startEnd(author):

        def a(fun):

            def b(name):

                print("this author is {0}".format(author))

                print("start")

                fun(name)

                print("end")

            return b

        return a

     

    @startEnd("lingxiangxiang")

    def hello(name):

        print("hello {0}".format(name))

    # hello = startEnd("lingxiangxiang")(hello)

    # hello("ajing")

     

    hello("ajing")

    1.4、匿名函数示例:

    匿名函数:f = lambda n: 1 if n <= 2 else f(n -1) + f(n - 2)

    这个函数拆分出来的就是:

    def f(n):

      if n <= 2:

        return 1

      else:

        return f(n - 1) + f(n - 2)

  • 相关阅读:
    iOS Graphics 编程
    如何用PHP/MySQL为 iOS App 写一个简单的web服务器(译) PART1
    Python服务器开发二:Python网络基础
    Access一些问题
    托管调试助手报错
    ConnectionString
    百度也开源
    Microsoft SQL Server 错误代号: 15535 解决方法
    临时表的一个用法
    类型初始值设定项引发异常
  • 原文地址:https://www.cnblogs.com/Jweiqing/p/8878358.html
Copyright © 2011-2022 走看看