十. 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)

'''

 

原文地址:https://www.cnblogs.com/ArrozZhu/p/8393676.html