zoukankan      html  css  js  c++  java
  • 十. Python基础(10)--装饰器

    十. Python基础(10)--装饰器

    1 ● 装饰器

    A decorator is a function that take a function as an argument and return a function.

    We can use a decorator to extend the functionality of an existing function without changing its source.

    Decorators are syntactic sugar.

    装饰器是一个函数, 它接受一个函数作为实参并且返回一个函数.

    我们可以用装饰器来扩充一个已经存在的函数的功能, 但又不修改其源码.

    装饰器是一种语法糖(syntactic sugar).

    The "@" symbol indicates to the parser that we're using a decorator while the decorator function name references a function by that name.

    在计算机科学中,语法糖(syntactic sugar)是指编程语言中 可以更容易地 表达 一个操作 的语法

    装饰器扩展至类:

    A decorator in Python is any callable Python object that is used to modify a function or a class. A reference to a function "func" or a class "C" is passed to a decorator and the decorator returns a modified function or class. The modified functions or classes usually contain calls to the original function "func" or class "C".

     

    2 ● 装饰器的模板

    def wrapper(func): # wrapper是装饰器的名字

        def inner(*args, **kwargs):

            print("被装饰的函数执行之前你要做的事.")

            ret = func(*args, **kwargs) # 被装饰的函数执行, 返回值为None也写出来

            print("被装饰的函数执行之后你要做的事.")

            return ret # ret有可能是None, 并且没有变量接收

        return inner

     

    @wrapper # 相当于welcome = wrapper(welcome)

    def welcome(name): # welcome是被装饰的函数

        print('Welcome:%s!'%name)

     

    @wrapper

    def home(): # home是被装饰的函数

        print('欢迎来到home页!')

     

    welcome("Arroz")

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

    home()

    参见: http://blog.csdn.net/qq_34409701/article/details/51589736

    def wrapper(func):

        def inner(*args, **kwargs):

            print("AAAAAAA")

            print(func(*args, **kwargs))

        return inner

     

    @wrapper

    def f1():

        return "f1"

     

    f1()

     

    '''

    AAAAAAA

    f1

    '''

     

    知识补充:

    1 ● eval()函数

    if name in locals():

        return eval(name)(*args)

    name是函数名, 后面的形参需要和一般函数名一样带括号(*args)

     

    2 ● 斐波那契数列停止的情况:

    # ① 长度小于多少

    '''

    l=[1,1]

    while len(l) < 20:

        l.append(l[-1]+l[-2])

        print(l)

    '''

    # ② 最后一个数小于多少

    '''

    l = [1,1]

    while l[-1] < 40000:

        l.append(l[-1] + l[-2])

        print(l)

    '''

     

  • 相关阅读:
    JS中使用正则表达式封装的一些常用的格式验证的方法-是否外部url、是否小写、邮箱格式、是否字符、是否数组
    Java中操作字符串的工具类-判空、截取、格式化、转换驼峰、转集合和list、是否包含
    Cocos2d-x 2.0 自适应多种分辨率
    应用自定义移动设备外观
    为移动设备应用程序创建外观
    【2020-11-28】人生十三信条
    【2020-11-27】事实证明,逃避是下等策略
    Python 之web动态服务器
    Python 之pygame飞机游戏
    PHP 之转换excel表格中的经纬度
  • 原文地址:https://www.cnblogs.com/ArrozZhu/p/8393676.html
Copyright © 2011-2022 走看看