Python高级编程(二)

迭代器(lterator)

可以直接作用于for循环的数据类型

判断是否可以迭代

from collections import Iterable
isinstance("abc", Iterable)      #判断是否可迭代
输出:
True
isinstance(100,Iterable)
输出:
False

iter()函数

生成器都是lterator对象,但是lterable不一定是迭代器对象,

list、dict、str等lterable变成iterator可以使用iter()函数

isinstance(iter("100"),Iterable)#不可迭代对象转换为可迭代对象
True

闭包

在函数内部再定义一个函数,并且这个函数用到了外边函数的变量
应用
def test(a, b):
    def test_in(x):
        if a == 0:
            print("X")
        else:
            print(a*x+b)

    return test_in

line1 = test(1, 1)
line1(0)
line2 = test(2, 2)
line2(4)
line1(5)
输出:
1
10
6
  • 好处在于a,b的值不需要每次传入x时都重新输入

装饰器

装饰器的优点

  • 无需修改被装饰的函数源代码
  • 无需修改被装饰函数的调用方式

装饰器的作用

装饰器是Python特有的方法,用于给某程序增添程序,但该程序已经上线或者使用,因此无法大批量的更改代码,所以用到了装饰器

装饰器的实现

def w1(func):
    def inner():
        print("2222222222")
        func()
    return inner
@w1   #相当于f1 = w1(f1)
def f1():
    print("f11111111")

f1()
输出:
2222222222
f11111111

多个装饰器

def makeBlod(fn):
    def wrapped():
        print("11111111111")
        return "<b>" + fn() + "</b>"
    return wrapped

def makeItalic(fn):
    def wrapped():
        print("22222222222")
        return "<i>" + fn() + "</i>"

    return wrapped

@makeBlod
@makeItalic
def test1():
    print("33333333333")
    return "hello world-1"
ret = test1()
print(ret)

通过下面的输出可以看到,当有多个装饰器的时候,装饰器运行是从下到上依次运行

输出:
11111111111
22222222222
33333333333
<b><i>hello world-1</i></b>

通用的装饰器

有无参数都可用

def func(functionName):
    def func_in(*args, **kwargs):
        ret = functionName(*args, **kwargs)
        return ret
    return func_in

作用域

命名空间

简单说命名空间是对变量名的分组划分,某个变量隶属于哪个空间内

globals、locals

  • globals()打印当前全局变量
  • locals()打印当前局部变量

LEGB规则

LEGB规则就是用来规定命名空间查找顺序的规则
即:LEGB规定了查找一个名称的顺序为:local-->enclosing function locals-->global-->builtin
原文地址:https://www.cnblogs.com/Burtit/p/8664205.html