bai|boyang

导航

 

python day4 学习整理

 

1.装饰器

什么是装饰器
器是指函数
装饰就是修饰,意思是为其他函数添加新功能
装饰器定义:本质就是函数,定义是为其他函数添加新功能

装饰器需要遵循的原则
1,不修改被装饰函数的源代码(开放封闭原则)
2,为被装饰函数添加新功能后,不修改被装饰函数的调用方式

实现装饰器的知识储备
装饰器 = 高阶函数 + 函数嵌套 + 闭包

 def foo(x):
   def foo1(x):
       return x
   return foo1

 print(foo(1))

 



 高阶函数定义: 1. 函数接收的参数是一个函数名 2. 函数的返回值是一个函数名 3 任意满足以上两点其中之一

def foo():
    print('我的函数名作为参数传给高阶函数')
def gaojie1(func):
    print('我就是高阶函数')
    func()
def gaojie2(func):
   print('我就是高阶函数')
   return func

gaojie1(foo)
gaojie2(foo)

import time
def foo():
    print('from the foo')

def timmer(func):
  start_time = time.time()
  return func
  stop_time = time.time()
  print('函数%s 运行时间是%s' %(func,stop_time-start_time))

timmer(foo)

 



函数嵌套

def father(name):
  print('from father %s' %(name))
def son():
  print('from son')
def grandson():
  print('from grandson')
  grandson()
  son()
  father('yangzuosheng')

闭包

def father(name):
  def son():
      name = 'alex'
       print('我爸爸是 [%s]' %name)
       def grandson():
          name = 'wupeiqi'
          print('我爷爷是 [%s]' %name)
       grandson()
   son()
father('yangzuosheng')

无参装饰器

def timer(func):
  def wrapper():
      func()
  return wrapper

加上参数

def timer(func):
  def wrapper(*args,**kwargs):
     func(*args,**kwargs)
  return wrapper()

加上功能

import time
def timer(func):
  def wrapper(*args,**kwargs):
     start_time = time.time()
     func(*args,**kwargs)
     stop_time = time.time()
     print('hanshu[%s],yunxingshijian[%s]' %(func,stop_time-start_time))
  return wrapper

加上返回值

import time
def timer(func):
   def wrapper(*args,**kwargs):
     start_time = time.time()
     res = func(*args,**kwargs)
     stop_time = time.time()
     print('hanshu[%s],yunxingshijian[%s]' %(func,stop_time-start_time))
     return res
   return wrapper

使用装饰器

def cal(array):
   res = 0
   for i in array:
   res+=i
   return res

cal=timer(cal)
cal(range(10))

语法糖@

@timer
def cal(array):
   res = 0
   for i in array:
   res+=1
   return res

cal(range(10))

装饰器应用实例1::::::::::无参装饰器

user_list=[{'name':'alex','passwd':'123'}{'name':'linhaifeng','passwd':'123'},
{'name':'wupeiqi','passwd':'123'},
{'name':'yuanhao','passwd':'123'},]
current_user={'username':None,'login':False}

def auth_deco(func):
   def wrapper(*args,**kwargs):
       if current_user['username'] and current_user['login']:
       res = func(*args,**kwargs)
       return res
   username = input('用户名:').strip()
   passwd = input('密码:').strip()

   for index,user_dic in enumerate(user_list):
      if username == user_dic['name'] and passwd == user_dic['passwd']:
        current_user['username'] = username
        current_user['login'] = True
        res = func(*args,**kwargs)
        return res
        break
     else:
        print('用户名或者密码错误,重新登陆')
        return wrapper
@auth_deco
def index():
  print('欢迎来到主界面')

@auth_deco
def home():
    print('这里是你家')


def shopping_cart():
   print('查看购物车啊亲')

def order():
   print('查看订单啊亲')

    print(user_list)

index()
print(user_list)
home()

 带参数装饰器++++++++++++++++
# user_list=[
# {'name':'alex','passwd':'123'},
# {'name':'linhaifeng','passwd':'123'},
# {'name':'wupeiqi','passwd':'123'},
# {'name':'yuanhao','passwd':'123'},
# ]
#
# current_user={'username':None,'login':False}
# def auth(auth_type='file'):
# def auth_deco(func):
# def wrapper(*args,**kwargs):
# if auth_type == 'file':
# if current_user['username'] and current_user['login']:
# res=func(*args,**kwargs)
# return res
# username=input('用户名: ').strip()
# passwd=input('密码: ').strip()
#
# for index,user_dic in enumerate(user_list):
# if username == user_dic['name'] and passwd == user_dic['passwd']:
# current_user['username']=username
# current_user['login']=True
# res=func(*args,**kwargs)
# return res
# break
# else:
# print('用户名或者密码错误,重新登录')
# elif auth_type == 'ldap':
# print('巴拉巴拉小魔仙')
# res=func(*args,**kwargs)
# return res
# return wrapper
# return auth_deco
#
#
# #auth(auth_type='file')就是在运行一个函数,然后返回auth_deco,所以@auth(auth_type='file')
# #就相当于@auth_deco,只不过现在,我们的auth_deco作为一个闭包的应用,外层的包auth给它留了一个auth_type='file'参数
# @auth(auth_type='ldap')
# def index():
# print('欢迎来到主页面')
#
# @auth(auth_type='ldap')
# def home():
# print('这里是你家')
#
# def shopping_car():
# print('查看购物车啊亲')
#
# def order():
# print('查看订单啊亲')
#
# # print(user_list)
# index()
# # print(user_list)
# home()

#####潮湿装饰器+++++++ egon 老师带你装逼带你飞,带你杵进垃圾堆,带你狂带你浪,带你哐哐撞大墙 ++++++++++++
# import sys,threading,time
#
#
# class KThread(threading.Thread):
#
# """A subclass of threading.Thread, with a kill()
#
# method.
#
#
#
# Come from:
#
# Kill a thread in Python:
#
# http://mail.python.org/pipermail/python-list/2004-May/260937.html
#
# """
#
# def __init__(self, *args, **kwargs):
#
# threading.Thread.__init__(self, *args, **kwargs)
#
# self.killed = False
#
#
#
# def start(self):
#
# """Start the thread."""
#
# self.__run_backup = self.run
#
# self.run = self.__run # Force the Thread to install our trace.
#
# threading.Thread.start(self)
#
#
#
# def __run(self):
#
# """Hacked run function, which installs the
#
# trace."""
#
# sys.settrace(self.globaltrace)
#
# self.__run_backup()
#
# self.run = self.__run_backup
#
#
#
# def globaltrace(self, frame, why, arg):
#
# if why == 'call':
#
# return self.localtrace
#
# else:
#
# return None
#
#
#
# def localtrace(self, frame, why, arg):
#
# if self.killed:
#
# if why == 'line':
#
# raise SystemExit()
#
# return self.localtrace
#
#
#
# def kill(self):
#
# self.killed = True
#
#
#
# class Timeout(Exception):
#
# """function run timeout"""
#
#
#
# def timeout(seconds):
#
# """超时装饰器,指定超时时间
#
# 若被装饰的方法在指定的时间内未返回,则抛出Timeout异常"""
#
# def timeout_decorator(func):
#
# """真正的装饰器"""
#
#
#
# def _new_func(oldfunc, result, oldfunc_args, oldfunc_kwargs):
#
# result.append(oldfunc(*oldfunc_args, **oldfunc_kwargs))
#
#
#
# def _(*args, **kwargs):
#
# result = []
#
# new_kwargs = { # create new args for _new_func, because we want to get the func return val to result list
#
# 'oldfunc': func,
#
# 'result': result,
#
# 'oldfunc_args': args,
#
# 'oldfunc_kwargs': kwargs
#
# }
#
# thd = KThread(target=_new_func, args=(), kwargs=new_kwargs)
#
# thd.start()
#
# thd.join(seconds)
#
# alive = thd.isAlive()
#
# thd.kill() # kill the child thread
#
# if alive:
#
# raise Timeout(u'function run too long, timeout %d seconds.' % seconds)
#
# else:
#
# return result[0]
#
# _.__name__ = func.__name__
#
# _.__doc__ = func.__doc__
#
# return _
#
# return timeout_decorator
#
#
# @timeout(5)
#
# def method_timeout(seconds, text):
#
# print('start', seconds, text)
#
# time.sleep(seconds)
#
# print('finish', seconds, text)
#
# return seconds
#
#
# method_timeout(6,'asdfasdfasdfas')


2 集合拾遗

# c1 = 'alex'
# c2 = 'alexsb'
# old_dict = {
# "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
# "#2":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
# "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
# }
#
# # cmdb 新汇报的数据
# new_dict = {
# "#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 800 },
# "#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
# "#4":{ 'hostname':c2, 'cpu_count': 2, 'mem_capicity': 80 },
# }
#
# old_set = set(old_dict.keys())
# update_list = list(old_set.intersection(new_dict.keys()))
#
# new_list = []
# del_list = []
#
# for i in new_dict.keys():
# if i not in update_list:
# new_list.append(i)
#
# for i in old_dict.keys():
# if i not in update_list:
# del_list.append(i)
# print(update_list)
# print(new_list)
# print(del_list)


# cd = Counter('abcdeabcdabcaba')
# print(cd)
# li = [13,22,6,99,11]
# for i in range(1,5):
# for m in range(len(li)-i):
# if li[m] > li[m+1]:
# tem = li[m+1]
# li[m+1] = li[m]
# li[m] = tem

# while True:
# num1 = input('num1:')
# num2 = input('num2:')
# try:
# num1 = int(num1)
# num2 = int(num2)
# result = num1 + num2
# except Exception as err:
# print('出现异常,信息如下:')
# print(err)

# dic = ['wuupeiqi','alex']
# try:
# dic[10]
# except Exception as err:
# print(err)

# dic = {'k1':'v1'}
# try:
# dic['k20']
# except KeyError as err:
# print(err)

# s1 = 'hello'
# try:
# int(s1)
# except ValueError as err:
# print(err)

# import time
# print(time.time())
# print(time.strftime("%Y-%m-%d %X"))
# print(time.localtime())
# print(time.gmtime())
# print(time.strftime("%Y-%m-%d %X", time.localtime()))
# print(time.strptime("2017-05-24 17:40:00", "%Y-%m-%d %X"))
# print(time.asctime())
# print(time.ctime())
# print(time.ctime(time.time()))

import random
# print(random.random())
# print(random.randint(1,3))
# print(random.randrange(1,3))
# print(random.choice([1,'23',[4,5]]))
# print(random.sample([1,'23',[4,5]],2))
# print(random.uniform(1,3))

# item = [1,2,3,4,5,6,8]
# random.shuffle(item)
# print(item)


##### 生成随机验证码
# import random
#
# def v_code():
# code = ''
# for i in range(0,9):
# num = random.randint(0,9)
# alf = chr(random.randint(65,90)) #chr()返回字符对应的ascii字符,参数可以是十进制的也可以是十六进制的
# add = random.choice([num,alf])
# code += str(add)
# return code
# print(v_code())

import os
# print(os.getcwd())

# import os,sys
# possible_topdir = os.path.normpath(os.path.join(
# os.path.abspath(__file__),
# os.pardir,
# os.pardir,
# os.pardir
# ))
# sys.path.insert(0,possible_topdir)
# 进度条
# import sys,time
# for i in range(50):
# sys.stdout.write('%s\r' %('#'*i))
# sys.stdout.flush()
# time.sleep(0.1)

#shutil模块

# import shutil
# shutil.copyfileobj(open('a','r'),open('b','w')) #将文件内容拷贝到另一个文件中
#
# shutil.copyfile('a','b') #目标文件无需存在
#
# shutil.copymode('a','b') #仅拷贝权限,内容,组,用户均不变,目标文件必须存在
#
# shutil.copystat('a','b') #仅拷贝状态的信息,包括:mode,bits,atime,mtime,flags
#
# shutil.copy('a','b') #拷贝文件和权限,
#
# shutil.copy2('a','b') #拷贝文件和状态信息,

# import json
# dic = {'name':'alvin','age':23,'sex':'male'}
# print(type(dic))
# j = json.dumps(dic)
# print(type(j))
# print(j)
#
# f = open('序列化对象','w')
# f.write(j)
# f.close()
#
# l = open('序列化对象')
# data = json.loads(l.read())
# print(data)
# l.close()

# import pickle
# dic = {'name':'alive', 'age':23,'sex':'male'}
# print(type(dic))
# j = pickle.dumps(dic)
# print(type(j))
# configparser模块
#
# import configparser
#
# config = configparser.ConfigParser()
# config.read('test.ini',encoding='utf-8')
# # res = config.sections() #获取所有节点
# # res1 = config.items('bitbucket.org') #获取制定节点下的所有的键值对
# # res2 = config.options('bitbucket.org') #获取指定节点下的所有的键
# # res3 = config.get('bitbucket.org','user') #获取指定节点下的所有的键
# # res4 = config.getint('topsecret.server.com','port') #获取指定节点下的所有的键
# # res5 = config.getfloat('topsecret.server.com','port') #获取指定节点下的所有的键
# # res6 = config.getboolean('topsecret.server.com','Forwardx11') #获取指定节点下的所有的键
# # print(res1)
# #检查节点
# # has_sec = config.has_section('bitbucket.org')
# # print(has_sec) #会打印true
#
# ###添加节点
# # config.add_section('egon') #已经存在则报错
# # config['egon']['username']='gangdan'
# # config['egon']['age']='1'
# # config.write(open('test.ini','w'))
#
# ###删除节点
# # config.remove_section('egon')
# # config.write(open('test.ini','w'))
#
# ###检查指定组内的键值对
# has_sec = config.has_option('bitbucket.org','user')
# print(has_sec) #打印true
#
# ###删除指定组内的键值对
# config.remove_option('DEFAULT','forwardx11')
# config.write(open('test.ini','w'))
#
# ###设置指定组内的键值对
# config.set('bitbucket.org','user','gangdan')
# config.write(open('test.ini','w'))

#####添加一个example.ini文档

# import configparser
# config = configparser.ConfigParser()
# config['DEFAULT'] = {'ServerAliveInterval':'45',
# 'Compression':'yes',
# 'CompressionLevel':'9'
# }
#
# config['bitbucket.log'] = {}
# config['bitbucket.log']['User'] = 'hg'
# config['topsecret.server.com'] = {}
# topsecret = config['topsecret.server.com']
# topsecret['Host Port'] = '50022'
# config['DEFAULT']['Forwardx11'] = 'yes'
# with open('example.ini','w') as configfile:
# config.write(configfile)

###hashlib
#
# import hashlib
# m = hashlib.md5()
# m.update('hello'.encode('utf-8'))
# print(m.hexdigest())
#
# a = hashlib.sh1
# 第一种方式
# import subprocess
# # res1 = subprocess.Popen('ls /Users/jieli/Desktop',shell=True,stdout=subprocess.PIPE)
# # res = subprocess.Popen('grep txt$',shell=True,stdin=res1.stdout,stdout=subprocess.PIPE)
# #
# # print(res.stdout.read().decode('utf-8'))
#
# # 第二种方式
# res1 = subprocess.Popen('ls /Users/jieli/Desktop |grep txt$',shell=True,stdout=subprocess.PIPE)
# print(res1.stdout.read().decode('utf-8'))

3 嵌套

ls = [1,2,3,4,5,6,7,8,45,66,77,88,99,333,555,999,1000]
def find_one(data,find_num):
print(data)

if len(data) > 1:
mid = int(len(data) / 2)
if data[mid] == find_num:
print("find", data[mid])
elif data[mid] < find_num:
print('找的数字在右边')
return find_one(data[mid+1:],find_num)
else:
print('找的数字在左边')
return find_one(data[0:mid],find_num)
else:
if data[0] == find_num:
print('find',data[0])
else:
print('cant find in list')

find_one(ls,1000)
# data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]


# def binary_search(dataset,find_num):
# print(dataset)
#
# if len(dataset) >1:
# mid = int(len(dataset)/2)
# if dataset[mid] == find_num: #find it
# print("找到数字",dataset[mid])
# elif dataset[mid] > find_num :# 找的数在mid左面
# print("\033[31;1m找的数在mid[%s]左面\033[0m" % dataset[mid])
# return binary_search(dataset[0:mid], find_num)
# else:# 找的数在mid右面
# print("\033[32;1m找的数在mid[%s]右面\033[0m" % dataset[mid])
# return binary_search(dataset[mid+1:],find_num)
# else:
# if dataset[0] == find_num: #find it
# print("找到数字啦",dataset[0])
# else:
# print("没的分了,要找的数字[%s]不在列表里" % find_num)
#
#
# binary_search(data,30)

4 迭代器

# res = lambda x:x**2
# print(res(2))

# res = lambda x,y:x if x > y else y
#
# print(res(2,3))
#迭代器协议是指对方必须提供一个next方法,执行方法要么返回迭代的下一项,要么就引起一个stopiteration异常,迭代终止
#可迭代的对象,是指实现了迭代器协议的对象(如何实现,内部定义了一个__iter__()__方法)
#协议是一种约定,可迭代对象实现了迭代器协议,python内部的工具(for,sum等)使用迭代器协议访问对象


# l = ['xx','yy','cc','aa']
# diedai_l = l.__iter__()
# # print(diedai_l.__next__())
# # print(diedai_l.__next__())
# # print(diedai_l.__next__())
# # print(diedai_l.__next__())
# # print(diedai_l.__next__())
# while True:
# try:
# print(diedai_l.__next__())
# except StopIteration:
# print('迭代器循环完毕,迭代终止了')
# break

# def lay_egg(num):
# egg_list = []
# for egg in range(num):
# egg_list.append('egg %s' %(egg))
# return egg_list
#
# yikuangdan = lay_egg(10)
# print(yikuangdan)

# def lay_eggs(num):
# for egg in range(num):
# res = 'egg %s' %(egg)
# yield res
# print('complete one egg')
#
# laomuji = lay_eggs(10)
# print(laomuji)
# print(laomuji.__next__())
# print(laomuji.__next__())
# print(laomuji.__next__())
# egg_1 = list(laomuji)
# print(egg_1)

# name = 'alex'
# # name = 'linghaifeng'
# res = 'SB' if name == 'alex' else 'shuai'
# print(res)

# egg_list = ['egg %s' %i for i in range(10)] #列表解析
# laomuji = ('egg %s' %i for i in range(10)) #生成器表达式
# print(laomuji)
# print(next(laomuji))
# print(laomuji.__next__())
# print(next(laomuji))
# print('<++++++++++>')
# print(egg_list)

# res = sum(x ** 2 for x in range(4))
# print(res)

# 迭代器的优点:延迟计算,一次一个返回结果,对于处理大数据量处理,将会非常有用
# 迭代器的优点2:能够有效提高代码可读性
#
# def index_words(text):
# result = []
# if text:
# result.append(0)
# for index, letter in enumerate(text,1):
# if letter == ' ':
# result.append(index)
# return result
#
# print(index_words('hello alex da sb'))
#
# def index_words(text):
# if text:
# yield 0
# for index, letter in enumerate(text,1):
# if letter == ' ':
# yield index
# g=index_words('hello alex da sb')
# print(g)
# print(g.__next__())
# print(g.__next__())
# print(g.__next__())
# print(g.__next__())
# print(g.__next__())
def get_provice_population(filaname):
with open(filaname,'r',encoding='utf-8') as f:
for line in f:
print(type(line))
p = eval(line)
yield p['population']
gen = get_provice_population('人口信息.txt')

all_population = sum(gen)
print(all_population)

5 生成器

什么是生成器?

可以理解为一种数据类型,这种数据类型自动实现了迭代器协议(其他的数据类型需要调用自己内置的__iter__方法),所以生成器就是可迭代对象

 

生成器分类及在python中的表现形式:(Python有两种不同的方式提供生成器)

1.生成器函数:常规函数定义,但是,使用yield语句而不是return语句返回结果。yield语句一次返回一个结果,在每个结果中间,挂起函数的状态,以便下次重它离开的地方继续执行

2.生成器表达式:类似于列表推导,但是,生成器返回按需产生结果的一个对象,而不是一次构建一个结果列表

 

为何使用生成器之生成器的优点

Python使用生成器对延迟操作提供了支持。所谓延迟操作,是指在需要的时候才产生结果,而不是立即产生结果。这也是生成器的主要好处。

 

生成器小结:

1.是可迭代对象

2.实现了延迟计算,省内存啊

3.生成器本质和其他的数据类型一样,都是实现了迭代器协议,只不过生成器附加了一个延迟计算省内存的好处,其余的可迭代对象可没有这点好处,记住喽!!!

 

__author__ = 'Linhaifeng'

def test():
for i in range(4):
yield i

g=test()

g1=(i for i in g)
g2=(i for i in g1)

print(list(g1))
print(list(g2))

 

posted on 2017-05-29 09:02  bai|boyang  阅读(305)  评论(0编辑  收藏  举报