Chico&Kiko

python基础之Day13

一、有参装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import time
current_user={'user':None}
def auth(engine='file'):
    def deco(func):
        def wrapper(*args,**kwargs)
            if current_user('user'):
                res=func(*args,**kwargs)
                return res
        user=input('username>>: ').strip()
        pwd=input('password>>: ').strip()
        if egine=='file':
            if user=='egon' and pwd=='123':
                print('login successful')
                current_user['user']=user
                res=func*args,**kwargs)
                 return res
            else:
                    print('user orr password error')
        elif engine == 'mysql':
                print('基于mysql的认证')
        elif engine == 'ldap':
                print('基于ldap的认证')
        else:
                print('无法识别认证来源')
        return wrapper
    return deco
 
@auth(engine='mysql'# @deco #index=deco(index) #index=wrapper
def index():
    print('welcome to index page')
    time.sleep(1)
 
@auth(engine='mysql')
def home(name):
    print('welecome %s to home page' %name)
    time.sleep(0.5)
 
 
index()
home('egon')               

 二、迭代器

什么是迭代器?

迭代器即迭代取值的工具

迭代:

  迭代是一个重复的过程,每一次重复都是基于上一次结果而来的

a)单纯的重复并不是迭代

while True:

  print(1)

b)迭代

l=['a','b','c']

def iterator(item):
  i=0
while i < len(item):
  print(l[i])
  i+=1

为什么要有迭代器

基于索引的迭代器取值方式只适用于列表、元组、字符串类型

而对于没有索引的字典、集合、文件则不在适用

所以必须找到一种通用的并且不依赖索引的迭代器取值方式-----》迭代器

迭代器适用于可迭代的类型

 

可迭代对象:

在Python中但凡内置有__iter__方法的对象都是可迭代的对象

字符串、列表、元组、字典、集合、文件都是可迭代对象

 

迭代器对象:指的是既有内置__iter__方法,又有内置__next__方法的对象

执行可迭代对象的__iter__方法得到的就是内置的迭代器对象

文件对象本身就是迭代器对象

 

注:

迭代器对象一定是可迭代对象,反之则不然

一旦迭代器取值取干净,再继续取就会抛出StopIteration

 

 

for 循环:迭代器循环

in后跟的一定是可迭代对象

 

迭代器对象:指的是既内置有__iter__方法,又内置有__next__方法的对象
 执行迭代器对象的__next__得到的是迭代器的下一个值
 执行迭代器对象的__iter__得到的仍然是迭代器本身

 

总结迭代器对象的优缺点:
优点:
1、提供了一种通用的、可以不依赖索引的迭代取值方式
2、迭代器对象更加节省内存

 缺点:
1、迭代器的取值不如按照索引的方式更灵活,因为它只能往后取不能往前退
2、无法预测迭代器值的个数

 
 
 

posted on 2018-06-20 10:56  Chico&Kiko  阅读(71)  评论(0编辑  收藏  举报

导航