十一. Python基础(11)—补充: 作用域 & 装饰器

十一. Python基础(11)—补充: 作用域 & 装饰器

1 ● Python的作用域补遗

在C/C++等语言中, if语句等控制结构(control structure)会产生新的作用域:

void
main()

{

    //int num = 10;

    if (2 > 1){

        int
num = 100;

    }

    printf("%d", num);

    getchar();

}

//在上面的案例中, printf("%d", num);中的num 会被警示未被声明.

但是, 在Python中, if语句等控制结构(control structure)不会产生新的作用域, 因此, 下面的程序在Python中是可以执行的.

if 2 > 1:

    num = 100

print(num) # 100

※ Python中, 只用三种语句块(block):

A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.

Python lacks declarations and allows name binding operations to occur anywhere within a code block.

 

2 ● 带参数的装饰器

def outer(flag):

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

        def inner(*args, **kwargs):

            if flag:

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

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

            if flag:

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

            return ret

        return inner

    return wrapper

 

@outer(False) # 传True表示不执行装饰器, 传False表示不执行装饰器

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

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

 

@outer(False) # 传True表示不执行装饰器, 传False表示不执行装饰器

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

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

 

welcome("Arroz")

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

home()

Welcome:Arroz!

===============================

欢迎来到home页!

 

3 ● 用多个装饰器装饰一个函数

def wrapper1(func):

    def inner():

        print("wrapper1, before func")

        func()

        print("wrapper1, after func")

    return inner

 

def wrapper2(func):

    def inner():

        print("wrapper2, before func")

        func()

        print("wrapper2, after func")

    return inner

 

@wrapper2

@wrapper1

def home():

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

 

home()

'''

wrapper2, before func

wrapper1, before func

欢迎来到home页!

wrapper1, after func

wrapper2, after func

'''

关键是要把握函数扩展功能的执行顺序

 

上一篇:winrar 授权破解过期解决


下一篇:How to build the Robotics Library from source code on Windows