python装饰器

装饰器实际是一个函数

一、定义: 在不改变内部代码和调用方式的基础上增加新的功能
二、了解装饰器需要先了解3个内容
1、函数即变量
2、高阶函数
   a、把一个函数名当做实参传给另一个函数
   b、返回值包含函数名
3、嵌套函数
 

高阶函数

  

import time
def  test():
    print('this is test func')
 
def deco(func):
     print('this is deco')
     func()             #test()
     return func
deco(test)
res = deco(test)
print(res)
 
 

嵌套函数(定义一个函数,)

def  test():
     def deco():
         print('this is test')
     deco()
res = test()
print(res)
 

  

装饰器说明

def deco(func):                 #func=test
    def wrapper():
        func()                #test()
        print('this is add')
    return wrapper  #返回wrapper的内存地址
(两个动作
1、是定义函数
2、返回值)
 
@deco   (装饰器)              #test= deco(test) wrapper的内存地址
def  test():
    print('this is test func')
test()
@deco =  ‘’test = deco(test)  test()  ‘’说明
def  test():
    print('this is test func')
test = deco(test)              #wrapper的内存地址
test()
装饰器原则:(在不改变内部代码和调用方式的基础上增加新的功能)所以接收返回值的变量必须为test
 
1、deco(test):wrapper的内存地址,,test接收deco(test)的返回值 ,也就是内存地址
2、test为内存地址,所以加括号就能运行 :test()
3、test()运行的是wrapper()
 

传参数

def deco(func):                           #func=test
    def wrapper(*args,**kwargs):
        func(*args,**kwargs)            #test()函数
        print('this is add')
    return wrapper  #返回wrapper的内存地址
 
@deco   (装饰器)      
def  test(name,age,job):
    print('this is test func %s qwe %s %s' %(name,age,job))
test('aaa',18,'IT')
 
 

迭代器

迭代:指的是一个重复的过程,每一次重复称为一次迭代,并且每次重复的结果是下一次重复的初始值
 
为什么要有迭代器
对于序列类型:字符串,列表,元组可以依赖于索引来迭代取值
但对于dict,set,文件,python必须为我们提供一种不依赖于素银取值的方法——迭代器
 
 
while取值
 
字符串
s = 'helloword'
i = 0
while i < len(s):
     print(s[i])
     i = i+1
 
列表、元组
i = 0
l = ['a','b','c','d']
# l = ('a','b','c','d')
while i < len(l):
     print(l[i])
     i = i+1
 
可迭代对象  name. __iter__()
 s = 'helloword'
 l = ['a','b','c','d']
 t = ('a','b','c','d')
 dict = {'name':'asdf','age':12,'job':'it'}
 set = {'a','b','c','d'}
 
s.__iter__()              #加__iter__()   就是把一个对象变成可迭代对象
l.__iter__()
t. __iter__()
dict. __iter__()
set. __iter__()             #都是可迭代对象
 
文件是迭代器对象
 f = open('a.txt','w',encoding='utf-8') 
 f. __iter__()
 
迭代器对象 name._items._   name.__next__()
 f.__iter__()            #本身就是一个可迭代对象
 f.__next__()
print(f is f.f.__iter__() )    #输出True 
 
 

取值

 d = {'name':'asdf','age':12,'job':'it'}
 d.__iter__()
 d_items = d.__iter__()          #转换为迭代器对象
 #每次重复的结果是下一次重复的初始值
res = d_items.__next__()
res1 = d_items.__next__()
res2 = d_items.__next__()
print(res)
print(res1)
print(res2)     #按顺序取值
while True:
     try:
         res = d_items.__next__()
         print(res)
    except StopIteration:  #报错跳出
         break
 
for不用迭代(自带)
i = 0
d = {'name':'asdf','age':12,'job':'it'}
for i in d:
     print(i)
 
 
原文地址:https://www.cnblogs.com/heiguu/p/10048640.html