函数嵌套,内置函数,闭包函数,迭代器,生成器,装饰器

'''
1 函数的嵌套调用
2 函数的嵌套定义
'''

# def max2(x,y):
#     return x if x > y else y
#
#
# def max4(a,b,c,d):
#     res1=max2(a,b)
#     res2=max2(res1,c)
#     res3=max2(res2,d)
#     return res3
#
# print(max4(10,99,31,22))



#函数的嵌套定义
def f1():

    def f2():
        print('from f2')
        def f3():
            print('from f3')
        f3()
    f2()


# f1()



# print(abs(-1))
# print(all([1,2,3]))
# print(all([0,2,3]))

# print(all(''))

# print(any([0,None,'',1]))
# print(any([0,None,'']))
# print(any([]))

# print(bin(3))
# print(hex(17))
# print(oct(9))

#0 None 空===》bool值为False,其余都为True

# def func():
#     pass
# print(callable(func))


# print(chr(68))
# print(ord('D'))


# res=complex(1+2j)
# print(res.real)
# print(res.imag)


#工厂函数
# dict
# int
# str
# set
# list

# l=[] #l=list([])
# list([1,2,3])
# list(['a'])
# list(['b'])


# l=[]
# print(dir(l)) #查看一个对象下面的属性
#
# print(help(l))

# print(divmod(1000,30))

# x=range(10)
# enumerate([1,2,3]).__next__()


# cmd='print("你瞅啥")'

# dic="{'a':1,'b':2}"
# d=eval(dic)
# print(type(d),d['a'])

# with open('user.db','w',encoding='utf-8') as f:
#     user_dic={'name':'egon','password':'123'}
#     f.write(str(user_dic))

# with open('user.db','r',encoding='utf-8') as f:
#     dic=f.read()
#     print(dic,type(dic))
#     dic=eval(dic)
#     print(dic['name'])



s={1,2} #s=set({1,2}) 定义可变集合

# s.add(3)
# print(s)

# s=frozenset({1,2}) # 定义不可变集合


#哈希:
# 1. 只要校验的内容一致,那hash得到结果永远一样
# 2. 不可逆
# 3. 只要采用的哈希算法一样,那无论被校验的内容有多长,hash的到的结果长度都一样
# print(hash('asdfasdfsadf'))
# print(hash('asdfasdfsadf'))

# x=1
# y=x
# print(id(x),id(y))
#
# print(x is y) #判断的是身份

# a=1
# b=1
# print(a == b)  #判断的是值



# print(max([1,2,3,4]))

# print(pow(10,2,3))

l=['a',4,2,3]
# for i in reversed(l):
#     print(i)
#
# print(list(reversed(l)))

# i=reversed(l)
# for x in i:
#     print(x)
# print(list(i))



# print(round(3.141542653589127134,4))



# l=['a','b','c','d','e']
# print(l[1:4:2])
# s=slice(1,4,2)
# print(l[s])


# vars() #等于locals()


# s='helloo'
# l=[1,2,3,4,5]
#
# z=zip(s,l)
# print(z)
# for i in z:
#     print(i)


# import time
#
#
# m=__import__('time') #以字符串的形式导入模块
#
# # m.sleep(3000)
#
#
# #面向对象里面讲
# super
#
# isinstance
# issubclass
#
#
# classmethod
# staticmethod
# property
#
# delattr
# hasattr
# getattr
# setattr


'''
闭包:
1. 定义在内部函数
2. 包含对外部作用域而非全局作用域的引用,
该内部函数就成为闭包函数
'''
#
# def f1():
#     x = 1
#     def f2():
#         print(x)
#
#     return f2
#
# f=f1()
# # print(f)
#
# x=100000000000000000000000000
# f()




#闭包应用:惰性计算

from urllib.request import urlopen

def index(url):
    def get():
        return urlopen(url).read()

    return get

oldboy=index('http://crm.oldboyedu.com')

# print(oldboy().decode('utf-8'))
# print(oldboy.__closure__[0].cell_contents)


# res=urlopen('http://crm.oldboyedu.com').read()
#
# print(res.decode('utf-8'))




x=1
# y=2
def f1():
    # x=1
    y=2
    def f2():
        print(x,y)
    return f2

f=f1()
print(f.__closure__[0].cell_contents)


'''
迭代器
迭代的概念:重复+上一次迭代的结果为下一次迭代的初始值
重复的过程称为迭代,每次重复即一次迭代,
并且每次迭代的结果是下一次迭代的初始值

'''


# while True: #只满足重复,因而不是迭代
#     print('====>')


#下面才为迭代
# l = [1, 2, 3]
# count = 0
# while count < len(l):  # 只满足重复,因而不是迭代
#     print('====>', l[count])
#     count += 1
#
# l = (1, 2, 3)
# count = 0
# while count < len(l):  # 只满足重复,因而不是迭代
#     print('====>', l[count])
#     count += 1

# s='hello'
# count = 0
# while count < len(s):
#     print('====>', s[count])
#     count += 1
#


#为什么要有迭代器?对于没有索引的数据类型,必须提供一种不依赖索引的迭代方式

#可迭代的对象:内置__iter__方法的,都是可迭代的对象

# [1,2].__iter__()
# 'hello'.__iter__()
# (1,2).__iter__()
#
# {'a':1,'b':2}.__iter__()
# {1,2,3}.__iter__()

#迭代器:执行__iter__方法,得到的结果就是迭代器,迭代器对象有__next__方法
# i=[1,2,3].__iter__()
#
# print(i)
#
# print(i.__next__())
# print(i.__next__())
# print(i.__next__())
# print(i.__next__()) #抛出异常:StopIteration


# i={'a':1,'b':2,'c':3}.__iter__()

# print(i.__next__())
# print(i.__next__())
# print(i.__next__())
# print(i.__next__())

# dic={'a':1,'b':2,'c':3}
# i=dic.__iter__()
# while True:
#     try:
#         key=i.__next__()
#         print(dic[key])
#     except StopIteration:
#         break



# s='hello'
# print(s.__len__())
#
# print(len(s))
#
# len(s)====== s.__len__()


s={'a',3,2,4}

# s.__iter__() #iter(s)

# i=iter(s)
# print(next(i))
# print(next(i))
# print(next(i))
# print(next(i))
# print(next(i))


#如何判断一个对象是可迭代的对象,还是迭代器对象
from collections import Iterable,Iterator

# 'abc'.__iter__()
# ().__iter__()
# [].__iter__()
# {'a':1}.__iter__()
# {1,2}.__iter__()

# f=open('a.txt','w')
# f.__iter__()


#下列数据类型都是可迭代的对象
# print(isinstance('abc',Iterable))
# print(isinstance([],Iterable))
# print(isinstance((),Iterable))
# print(isinstance({'a':1},Iterable))
# print(isinstance({1,2},Iterable))
# print(isinstance(f,Iterable))



#只有文件是迭代器对象
# print(isinstance('abc',Iterator))
# print(isinstance([],Iterator))
# print(isinstance((),Iterator))
# print(isinstance({'a':1},Iterator))
# print(isinstance({1,2},Iterator))
# print(isinstance(f,Iterator))



'''
可迭代对象:只有__iter__方法,执行该方法得到的迭代器对象

迭代协议:
    对象有__next__
    对象有__iter__,对于迭代器对象来说,执行__iter__方法,得到的结果仍然是它本身


'''
# f1=f.__iter__()
#
# print(f)
# print(f1)
# print(f is f1)

#
# l=[]
# i=l.__iter__()
#
# print(i.__iter__())
# print(i)
# print(l)


dic={'name':'egon','age':18,'height':'180'}
# print(dic.items())

# for k,v in dic.items():
#     print(k,v)

# i=iter(dic)
# while True:
#     try:
#         k=next(i)
#         print(k)
#     except StopIteration:
#         break
# for k in dic: #i=iter(dic)  k=next(i)
#     print(k)
#     print(dic[k])
#



# l=['a','b',3,9,10]
# for i in l:
#     print(i)



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


'''
迭代器的优点和缺点
优点:
    1.提供了一种不依赖下标的迭代方式
    2.就跌迭代器本身来说,更节省内存

缺点:
    1. 无法获取迭代器对象的长度
    2. 不如序列类型取值灵活,是一次性的,只能往后取值,不能往前退
'''
# l=[10000,2,3,4,5]
#
# i=iter(l)
#
# print(i)
# print(next(i))
#
# f=open('a.txt',encoding='utf-8')
#
# for line in f.readlines():
#     print(line)

# print(next(f))

# for line in f:
#     print(line)




# l=[10000,2,3,4,5]
#
# i=iter(l)
#
# for item in i:
#     print(item)
# print('=============================')
#
#
# for item in i:
#     print(item)

l=[10000,2,3,4,5]

i=enumerate(l)

print(next(i))
print(next(i))



#生成器函数:只要函数体包含yield关键字,该函数就是生成器函数
#生成器就是迭代器

# def foo():
#     return 1
#     return 2
#     return 3
#     return 4
#
# res1=foo()
# print(res1)
#
# res2=foo()
# print(res2)





# def foo():
#     print('first')
#     yield 1
#     print('second')
#     yield 2
#     print('third')
#     yield 3
#     print('fourth')
#     yield 4
#     print('fifth')
#
# g=foo()
# for i in g:
#     print(i)



# print(g)
#
# print(next(g)) #触发迭代器g的执行,进而触发函数的执行
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))




# def counter(n):
#     print('start...')
#     i=0
#     while i < n:
#         yield i
#         i+=1
#     print('end...')
#
#
# g=counter(5)
# print(g)
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))








'''
yield的功能:
    1.相当于为函数封装好__iter__和__next__
    2.return只能返回一次值,函数就终止了,
    而yield能返回多次值,每次返回都会将函数暂停,下一次next会从
    上一次暂停的位置继续执行


'''

#tail -f a.txt | grep 'python'


import time
def tail(filepath):
    with open(filepath,encoding='utf-8') as f:
        f.seek(0,2)
        while True:
            line=f.readline().strip()
            if line:
                yield line
            else:
                time.sleep(0.2)




# t=tail('a.txt')
#
# for line in t:
#     print(line)

def grep(pattern,lines):
    for line in lines:
        if pattern in line:
            yield line


g=grep('python',tail('a.txt'))
print(g)

for i in g:
    print(i)



'''
装饰器:修饰别人的工具,修饰添加功能,工具指的是函数

装饰器本身可以是任何可调用对象,被装饰的对象也可以是任意可调用对象


为什么要用装饰器:
    开放封闭原则:对修改是封闭的,对扩展是开放的
    装饰器就是为了在不修改被装饰对象的源代码以及调用方式的前提下,为期添加新功能

'''




# import time
#
# def timmer(func):
#     def wrapper(*args,**kwargs):
#         start_time=time.time()
#         res=func(*args,**kwargs)
#         stop_time=time.time()
#         print('run time is %s' %(stop_time-start_time))
#     return wrapper
#
# @timmer
# def index():
#
#     time.sleep(3)
#     print('welcome to index')
#
# index()



# import time
#
# def timmer(func):
#     def wrapper():
#         start_time=time.time()
#         func() #index()
#         stop_time=time.time()
#         print('run time is %s' %(stop_time-start_time))
#     return wrapper
#
#
# @timmer #index=timmer(index)
# def index():
#     time.sleep(3)
#     print('welcome to index')
#
#
# # f=timmer(index)
# # # print(f)
# # f() #wrapper()---->index()
#
# # index=timmer(index) #index==wrapper
#
# index() #wrapper()----->



#流程分析
# import time
# def timmer(func):
#     def wrapper():
#         start_time=time.time()
#         func()
#         stop_time=time.time()
#         print('run time is %s' %(stop_time-start_time))
#     return wrapper
#
# @timmer #index=timmer(index)
# def index():
#     time.sleep(3)
#     print('welcome to index')
#
#
# index() #wrapper()








# import time
# def timmer(func):
#     def wrapper(*args,**kwargs):
#         start_time=time.time()
#         res=func(*args,**kwargs)
#         stop_time=time.time()
#         print('run time is %s' %(stop_time-start_time))
#         return res
#     return wrapper
#
# @timmer #index=timmer(index)
# def index():
#     time.sleep(3)
#     print('welcome to index')
#     return 1
#
# @timmer
# def foo(name):
#     time.sleep(1)
#     print('from foo')
#
#
# res=index() #wrapper()
# print(res)
#
# res1=foo('egon')  #res1=wrapper('egon')
# print(res1)
#
#

# def auth(func):
#     def wrapper(*args,**kwargs):
#         name=input('>>: ')
#         password=input('>>: ')
#         if name == 'egon' and password == '123':
#             print('\033[45mlogin successful\033[0m')
#             res=func(*args,**kwargs)
#             return res
#         else:
#             print('\033[45mlogin err\033[0m')
#     return wrapper
#
#
#
# @auth
# def index():
#     print('welcome to index page')
# @auth
# def home(name):
#     print('%s welcome to home page' %name)
#
# index()
# home('egon')
#


# login_user={'user':None,'status':False}
# def auth(func):
#     def wrapper(*args,**kwargs):
#         if login_user['user'] and login_user['status']:
#             res=func(*args,**kwargs)
#             return res
#         else:
#             name=input('>>: ')
#             password=input('>>: ')
#             if name == 'egon' and password == '123':
#                 login_user['user']='egon'
#                 login_user['status']=True
#                 print('\033[45mlogin successful\033[0m')
#                 res=func(*args,**kwargs)
#                 return res
#             else:
#                 print('\033[45mlogin err\033[0m')
#     return wrapper
#
# @auth
# def index():
#     print('welcome to index page')
# @auth
# def home(name):
#     print('%s welcome to home page' %name)
# index()
# home('egon')




























#========================有参装饰器
import time
def timmer(func):
    def wrapper(*args,**kwargs):
        print('====>timmer.wrapper')
        start_time=time.time()
        res=func(*args,**kwargs) #auth_wrapper
        stop_time=time.time()
        print('run time is %s' %(stop_time-start_time))
        return res
    return wrapper



login_user={'user':None,'status':False}
def auth(driver='file'):
    def auth2(func):
        def wrapper(*args,**kwargs):
            print('=======>auth.wrapper')
            time.sleep(5)
            if driver == 'file':
                if login_user['user'] and login_user['status']:
                    res=func(*args,**kwargs)
                    return res
                else:
                    name=input('>>: ')
                    password=input('>>: ')
                    if name == 'egon' and password == '123':
                        login_user['user']='egon'
                        login_user['status']=True
                        print('\033[45mlogin successful\033[0m')
                        res=func(*args,**kwargs)
                        return res
                    else:
                        print('\033[45mlogin err\033[0m')
            elif driver == 'ldap':
                print('==========ldap的认证')
            elif driver == 'mysql':
                print('==========mysql的认证')
                return func(*args,**kwargs)
            else:
                print('=========未知的认证来源')
        return wrapper
    return auth2


@auth('file') #@auth2====>index=auth2(index)===>index=auth_wrapper
@timmer #index=timmer(auth_wrapper) #index=timmer_wrapper
def index():
    time.sleep(3)
    print('welcome to index page')
@auth(driver='mysql')
def home(name):
    print('%s welcome to home page' %name)
index() #timmer_wrapper()
# home('egon') #wrapper('egon')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值