There python learning participation decorated with iterators

1, there is reference decorator

1.1 knowledge base

1.1.1 limit parameters

1) due to the limitation of @ syntactic sugar, the outter only one function parameter, and is used only to receive the memory address of the object decorated

def outter(func):
    # func = 函数的内存地址
    def wrapper(*args,**kwargs):
        res=func(*args,**kwargs)
        return res
    return wrapper
# @outter # index=outter(index) # index=>wrapper

@outter # outter(index)
def index(x,y):
    print(x,y)

2) After the back door
what it was like index of parameters, the parameters wrapper should look like
index of what the return value, the return value of the wrapper should look like
index attributes look like, wrapper attributes should look like == "from functools import wraps

1.2 play a mountain artillery:

def auth(func,db_type):
    def wrapper(*args, **kwargs):
        name=input('your name>>>: ').strip()
        pwd=input('your password>>>: ').strip()

        if db_type == 'file':
            print('基于文件的验证')
            if name == 'egon' and pwd == '123':
                res = func(*args, **kwargs)
                return res
            else:
                print('user or password error')
        elif db_type == 'mysql':
            print('基于mysql的验证')
        elif db_type == 'ldap':
            print('基于ldap的验证')
        else:
            print('不支持该db_type')
    
    return wrapper

# @auth  # 账号密码的来源是文件

def index(x,y):
    print('index->>%s:%s' %(x,y))

# @auth # 账号密码的来源是数据库

def home(name):
    print('home->>%s' %name)

# @auth # 账号密码的来源是ldap

def transfer():
    print('transfer')


index=auth(index,'file')
home=auth(home,'mysql')
transfer=auth(transfer,'ldap')

index(1,2)
home('egon')
transfer()

1.3 play two mountain artillery

def auth(db_type):
    def deco(func):
        def wrapper(*args, **kwargs):
            name=input('your name>>>: ').strip()
            pwd=input('your password>>>: ').strip()

            if db_type == 'file':
                print('基于文件的验证')
                if name == 'egon' and pwd == '123':
                    res = func(*args, **kwargs)
                    return res
                else:
                    print('user or password error')
            elif db_type == 'mysql':
                print('基于mysql的验证')
            elif db_type == 'ldap':
                print('基于ldap的验证')
            else:
                print('不支持该db_type')
    
        return wrapper
    return deco

deco=auth(db_type='file')
@deco # 账号密码的来源是文件
def index(x,y):
    print('index->>%s:%s' %(x,y))

deco=auth(db_type='mysql')
@deco # 账号密码的来源是数据库
def home(name):
    print('home->>%s' %name)

deco=auth(db_type='ldap')
@deco # 账号密码的来源是ldap
def transfer():
    print('transfer')


index(1,2)
home('egon')
transfer()

1.4 syntactic sugar

def auth(db_type):
    def deco(func):
        def wrapper(*args, **kwargs):
            name = input('your name>>>: ').strip()
            pwd = input('your password>>>: ').strip()

            if db_type == 'file':
                print('基于文件的验证')
                if name == 'egon' and pwd == '123':
                    res = func(*args, **kwargs)  # index(1,2)
                    return res
                else:
                    print('user or password error')
            elif db_type == 'mysql':
                print('基于mysql的验证')
            elif db_type == 'ldap':
                print('基于ldap的验证')
            else:
                print('不支持该db_type')
        return wrapper
    return deco


@auth(db_type='file')  # @deco # index=deco(index) # index=wrapper
def index(x, y):
    print('index->>%s:%s' % (x, y))

@auth(db_type='mysql')  # @deco # home=deco(home) # home=wrapper
def home(name):
    print('home->>%s' % name)

@auth(db_type='ldap')  # 账号密码的来源是ldap
def transfer():
    print('transfer')

index(1, 2)
home('egon')
transfer()

1.5 There decorator template parameters

def 有参装饰器(x,y,z):
    def outter(func):
        def wrapper(*args, **kwargs):
            res = func(*args, **kwargs)
            return res
        return wrapper
    return outter

@有参装饰器(1,y=2,z=3)
def 被装饰对象():
    pass

2, iterators

2.1 What is an iterator

Iterator refers to the value of the iteration tools, iteration is an iterative process, each iteration
is based on a result of continued, not simply repeat iteration

2.2 Why have iterators

Iterator iterative value is used tool, and a plurality of values related to the type of cycles taken out
are: a list of strings, tuples, dictionaries, set, open the file

l=['egon','liu','alex']
i=0
while i < len(l):
    print(l[i])
    i+=1

Iterative manner described above apply only to the value of the indexed data types: list, string, a tuple
order to address the limitations based on the index value of the iterator
python must be provided without depending on the way the index value, which is iterator

2.3 How iterator

2.3.1 Iterative object: Whenever there is built-in objects are called methods may __iter__ iteration

s1=''

# s1.__iter__()

l=[]

# l.__iter__()

t=(1,)

# t.__iter__()

d={'a':1}

# d.__iter__()

set1={1,2,3}

# set1.__iter__()

with open('a.txt',mode='w') as f:
    # f.__iter__()
    pass

2.3.2 __iter__ method in object can call the iterator will convert iterator object

d={'a':1,'b':2,'c':3}
d_iterator=d.__iter__()
print(d_iterator)

print(d_iterator.__next__())
print(d_iterator.__next__())
print(d_iterator.__next__())
print(d_iterator.__next__()) # 抛出异常StopIteration


while True:
    try:
        print(d_iterator.__next__())
    except StopIteration:
        break

print('====>>>>>>') # 在一个迭代器取值取干净的情况下,再对其取值娶不到
d_iterator=d.__iter__()
while True:
    try:
        print(d_iterator.__next__())
    except StopIteration:
        break


l=[1,2,3,4,5]
l_iterator=l.__iter__()

while True:
    try:
        print(l_iterator.__next__())
    except StopIteration:
        break

2.4 iterables the iterator object Detailed

2.4.1 iterables ( "can be converted into an iterator object"): Method objects built __iter__

. Iterables ITER (): iterator object obtained

2.4.2 iterator object: a built __next__ method and built-in objects have methods __iter__

Iterator object .__ next __ (): get the iterator next value
iterator object .__ iter __ (): get the iterator itself, it plainly did not adjust the tone with a look

dic={'a':1,'b':2,'c':3}

dic_iterator=dic.__iter__()
print(dic_iterator is dic_iterator.__iter__().__iter__().__iter__())

2.4.3 iterables: strings, lists, tuples, dictionaries, collections, file objects

Iterator objects: file object

s1=''
s1.__iter__()

l=[]
l.__iter__()

t=(1,)
t.__iter__()


d={'a':1}
d.__iter__()

set1={1,2,3}
set1.__iter__()


with open('a.txt',mode='w') as f:
    f.__iter__()
    f.__next__()

Works 2.5 for loop: for loop can call call the iterator loop

d={'a':1,'b':2,'c':3}

1) d.iter () to get a iterator object
2) iterator object .next () get a return value, the return value is then assigned to K
. 3) Step 2 the cycle, until the for loop will raise StopIteration catch an exception and ends the cycle

for k in d:
    print(k)


with open('a.txt',mode='rt',encoding='utf-8') as f:
    for line in f: # f.__iter__()
        print(line)


list('hello') #原理同for循环

2.6 summarizes the advantages and disadvantages of iterator

2.6.1 Disadvantages:

I, provides a unified way the value of iterative sequence and non-sequence types.
II, lazy evaluation: iterator object is represented by a data stream, you can only when needed to call the next to calculate a value, it is the iterator itself, only one value at a time in memory, which can store unlimited large data stream, but other container types, such as lists, all the elements need to be stored in memory, restricted memory size, the number of values can be stored is limited.

2.6.2 Disadvantages:

I, unless depletion, or can not get the iterator length

II, can only remove a value, not back to the beginning, more like a 'one-off', the only goal is to repeat the iterator produce the next method until the value of depletion, otherwise it will stay in one place, waiting for the next a call next; if you want iterations of the same object again, you can only recall iter method to create a new iterator object, if there are two or more cycles using the same iterator, inevitably there will only be able to get into a cycle value.

3, the generator

3.1 How to get custom iterators:

Once the yield keyword in the presence of a function, the function does not perform calling function body
returns an object generation, i.e., the iterator custom generator

def func():
    print('第一次')
    yield 1
    print('第二次')
    yield 2
    print('第三次')
    yield 3
    print('第四次')

g=func()
print(g)

3.2 generator iterators

g.__iter__()
g.__next__()

Can trigger a function body code, then encounters yield stopped, the value of yield
as a result of this call returns

res1=g.__next__()
print(res1)

res2=g.__next__()
print(res2)

res3=g.__next__()
print(res3)

res4=g.__next__()



len('aaa') # 'aaa'.__len__()

next(g)    # g.__next__()
iter(可迭代对象)     # 可迭代对象.__iter__()

3.3 Application Case column

def my_range(start,stop,step=1):

    # print('start...')

	while start < stop:
		yield start
		start+=step

    # print('end....')

g=my_range(1,5,2) # 1 3
print(next(g))
print(next(g))
print(next(g))

for n in my_range(1,7,2):
    print(n)

3.4 summarizes the yield:

With the yield keyword, we have a way to achieve self-defined iterator. yield may be used to return values, but unlike the return, the function return is encountered once ended, and the yield can keep a running state function suspend function to return multiple values

Guess you like

Origin www.cnblogs.com/leilijian/p/12562311.html