大小孩

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

本节内容

  1. 装饰器 Decorator(重点)
  2. 迭代器 Iterator
  3. 生成器 Generator
  4. 异常处理
  5. 内置函数
  6. 序列化与反序列化
  7. 软件目录结构设计
  8. 程序的解耦

一、装饰器 Decorator(重点)

本质是函数(装饰其他函数),为其他函数添加附加功能

(1) 原则

  • 不能修改被装饰函数的原代码(对被装饰函数来说装饰器是透明的)
  • 不能修改被装饰函数的调用方式

(2) 实现

实现方式:高阶函数 + 嵌套函数 –> 装饰器
  • 函数即变量:函数名是内存中函数体的引用(内存中引用计数为0时会被Python解释器定期清理)
  • 高阶函数:把一个函数名当做实参传给另外一个函数(在不修改被装饰函数原代码的情况下为其添加功能);返回值中包含函数名(不修改被装饰函数的调用方式)
  • 嵌套函数:在一个函数中调用一个函数

(3) 示例

1) 示例1

import time  
def timmer(func):  
    def warpper(*args,**kwargs):  
        start_time=time.time()  
        func(*args,**kwargs)  
        stop_time=time.time()  
        print('the func run time is %s' %(stop_time-start_time))  
    return warpper              #返回wapper内存地址  
     
@timmer    #添加在要修饰的函数之前,等同于test1=timmer(test1)  
def test1():  
    time.sleep(3)  
    print('in the test1')  
     
@timmer    #添加在要修饰的函数之前,等同于test2=timmer(test2)  
def test2(name):  
    time.sleep(3)  
    print('in the test2,%s'%name)  
      
test1()  
test2('alisa')

2) 示例2

user,passwd = '01001','abc123'  
def auth(auth_type):  
    print("auth func:",auth_type)  
    def outer_wrapper(func):  
        def wrapper(*args, **kwargs):  
            print("wrapper func args:", *args, **kwargs)  
            if auth_type == "local":  
                username = input("Username:").strip()  
                password = input("Password:").strip()  
                if user == username and passwd == password:  
                    print("\033[32;1mUser has passed authentication\033[0m")  
                    res = func(*args, **kwargs)  # from home  
                    print("---after authenticaion ")  
                    return res  
                else:  
                    exit("\033[31;1mInvalid username or password\033[0m")  
            elif auth_type == "ldap":  
                print("搞毛线ldap,不会。。。。")  
      
        return wrapper  
    return outer_wrapper  
      
def index():  
    print("welcome to index page")  
     
@auth(auth_type="local") # home = wrapper()  
def home():  
    print("welcome to home  page")  
    return "from home"  
     
@auth(auth_type="ldap")  
def bbs():  
    print("welcome to bbs  page")  
      
index()  
print(home()) #wrapper()  
bbs() 

二、迭代器 Iterator

可迭代对象(Iterable):可直接作用于for循环的对象。
  • 集合数据类型,如listlist,tuple,dict,set,str等
  • generator,包括生成器和带yield的generator function
可以使用isinstance()判断一个对象是否是Iterable对象。
迭代器Iterator:可以被__next__()函数调用并不断返回下一个值的对象。

三、生成器 Generator

(1) 定义

生成器:边循环边计算的机制(只记得当前的一个数据)。
  • 只有在调用时才会生成相应的数据(for循环)
  • 只记录当前位置,只有一个__next__()方法

(2) 列表生成式

#列表生成式  
print([i*2 for i in range(10)])  #结果[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]  
      
#for循环  
a = []  
for i in range(10):  
    a.append(i*2)  
print(a) 

(3) 生成方式

1) 生成式

#只有被调用的时候才开始计算  
c = (i*2 for i in range(1000000))  
print(c)   #结果 at 0x000002AD30D0DF10>  

2) 函数

#斐波那契  
def fib(max): #10  
    n, a, b = 0, 0, 1  
    while n < max: #n

四、异常处理

抓取程序运行时的异常并进行处理,避免程序直接抛出错误。

(1) 基本使用

while True:  
    try:  
        print('运行代码')  #要执行的代码  
    except StopIteration as e:       #抓取异常StopIteration  
        print(e)  
        break  
    except Exception as e:          #可以抓取所有所有异常  
        print(e)  
    finally:  
        print('无论有没有异常都执行')  #无论有没有异常都执行     

(2) 自定义异常

class HQError(Exception):  
    def __init__(self, msg):  
        self.message = msg  
    # def __str__(self):  
    #     return 'sdfsf'  
try:  
    raise HQError('数据库连不上')     #手动触发异常  
except HQError as e:  
    print(e)  

五、内置函数

Python自带了大量的内置函数,不用导入即可使用,如下图所示:

内置参数详解 https://docs.python.org/3/library/functions.html?highlight=built#ascii
#内置函数基本功能介绍
abs()   #求绝对值  
all()   #其中所有元素为真返回True  
any()   #其中有一个元素为真返回True  
ascii() #转成字符串  
bin()   #转成二进制  
bool()  #判断是不是布尔值  
bytearray() #把二进制字符串转成数组形式  
callable()  #判断是否可调用  
chr(98) #打出ASCII码表中对应项  
ord('d')    #取元素在ASCII表中位置  
    
compile(code,"err.log",'exec')  #编译  
exec(code)      #执行,code为代码文件  
    
delattr()  
dir()       #打印可用方法  
divmod(5,3)    #结果(1,2),商余(除法)  
enumerate()  
eval()  #把数据转换成字符串  
    
res = filter(lambda n:n>5,range(10))  #过滤  
for i in res:  
    print(i)  
    
res = map(lambda n:n*n,range(10)) #处理,res=[lambda i:i*2 for i in range(10)] ,[i*2 for i in range(10)]  
for i in res:  
    print(i)  
    
import functools #化简Python3  
res = functools.reduce(lambda x,y:x+y,range(10))  
print(res)  
    
frozenset() #生成不可变集合  
getattr()  
globals()   #当前程序所有全部变量(key:value形式)  
hash()  #转换成数字  
help()  #帮助  
hex()   #把数字转换成十六进制  
id()    #返回内存地址  
locals()    #返回局部变量  
next()  #相当于__next__()  
oct()   #转八进制  
ord()   #10行  
pow(2,8)    #2的8次方  
repr()  #转成字符串  
reversed()  #反转  
round(1.3342,2)     #保留两位小数  
sorted()        #排序  
staticmethod()  
str()  
sum()  
super()     #class继承__init__()  
tuple()  
type()  
vars(object)    #返回对象所有属性名  
    
zip()   #拉链  
a,b=[1,2,3,4],['a','b','c']  
for i in zip(a,b):  
    print(i)  
''''' 
(1,'a') 
(2,'b') 
(3,'c') 
'''  

六、序列化与反序列化

(1) json

1) 作用与特点

  • 不同语言之间进行数据交互
  • 只能处理简单的数据类型

2) 示例

#json序列化  
import json  
    
def sayhi(name):  
    print("hello,",name)  
    
info = {  
    'name':'01001',  
    'age':22,  
    #'func':sayhi  
}  
    
f = open("test.text","w")  
f.write( json.dumps( info) )  
    
info['age'] = 21  
f.write( json.dumps( info) )   #json序列化
    
f.close()  


#json反序列化
import json  
    
f = open("test.text","r")  
    
#data = json.loads(f.read()) #data = pickle.loads(f.read())  
    
for line in f:  
    print(json.loads(line))    #json反序列化

(2) pikle

1) 特点

  • 可以序列化Python所有的数据类型
  • 只能在Python中使用

七、软件目录结构设计

规范化能更好的控制程序结构,让程序具有如下优点:
  • 可读性高
  • 可维护性高
具体参考 http://www.cnblogs.com/alex3714/articles/5765046.html

八、程序的解耦

把可能会被其他程序用到的部分拆分开,写成可重复调用的模块:
  • 降低用户逻辑层后台之间紧密程度
  • 提升可扩展性(修改后台时应尽量不影响用户部分)

参考:

http://www.cnblogs.com/alex3714/articles/5740985.html
http://www.cnblogs.com/alex3714/articles/5765046.html
posted on 2017-12-20 22:25  大小孩  阅读(188)  评论(0)    收藏  举报