博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python_day4
阅读量:35194 次
发布时间:2020-01-31

本文共 4755 字,大约阅读时间需要 15 分钟。

一、装饰器

(为其他函数添加附加功能)

1、原则:

  •    不能修改被装饰函数的源代码
  •   不能修改被装饰函数的调用方式

2、储备知识:

  •     函数即“变量”
  •     高阶函数
  •     嵌套函数

  高阶函数+嵌套函数=装饰器

 

 

1 #Author : Felix Li 2  3 # 高阶函数的应用1 4 # import time 5 # def bar(): 6 #     time.sleep(1) 7 #     print("in the bar") 8 # def test1(func): 9 #     s_time=time.time()10 #     print(func)11 #     func()12 #     o_time=time.time()13 #     print("运行时间是%s"%(o_time-s_time))14 # test1(bar)15 16 #高阶函数的应用217 # import time18 # def bar():19 #     time.sleep(2)20 #     print("打印这个bar")21 # def test2(func):22 #     print(func)23 #     return func  #返回的是值24 # bar=test2(bar)25 # bar()
高阶函数

 

1 #嵌套函数 2  3 x=1; 4 def grandpa(): 5     #x=2; 6     def father(): 7         #x=3; 8         def son(): 9             #x=4;10             print(x)  #就近原则11         son()12     father()13 grandpa()
嵌套函数
1 #Author : Felix Li 2                   #装饰器示例1 3 import time 4 def timer(func):                 #这个高阶函数+嵌套函数  就是装饰器 5     def deco(*args, **kwargs): 6         s_time = time.time() 7         func(*args, **kwargs)   #运行 test1  和 运行test2 8         o_time = time.time() 9         print("这个程序的运行时间是%s" % (o_time-s_time))10     return deco11 12 @timer13 def test1():14     time.sleep(2)15     print("这是1的测试结果")16 17 @timer18 def test2(name, age):19     time.sleep(2)20     print("信息:", name, age)21 22 test1()23 test2("FELIX", 23)
装饰器示例1
1 #Author : Felix Li 2             #装饰器示例2 3  4 user,passwd ='felix','123' 5  6 def dec_1(auth_type): 7     print("auth func:",auth_type) 8     def outer_wrapper(func): 9         def wrapper(*args, **kwargs):10             print("wrapper func args:",*args,**kwargs)11             if auth_type=="local":12                 username = input("用户名:").strip()13                 password = input("密码:").strip()14 15                 if user == username and passwd == password:16                     print("用户名密码正确!")17                     return func(*args, **kwargs)18                 else:19                     exit("非法的用户名或密码")20             elif auth_type=="ldap":21                 print("老子不会了!。。。")22 23         return wrapper24     return outer_wrapper25 26 27 def index():28     print("欢迎进入本网站!")29 30 @dec_1(auth_type="local")31 def home():32     print("登陆成功!")33     return "from home!"34 @dec_1(auth_type="ldap")35 def bbs():36     print("欢迎进入论坛!")37 38 index()39 print(home())40 bbs()
装饰器示例2

 

二、迭代器与生成器

1、列表生成式

   [ i*2 for i in range(10)]

 

2、生成器

  •    只有在调用时才会生成相对应的数据
  •    只记录当前位置
  •    只有一个--next()--方法
1 #Author : Felix Li 2  3 import time 4 def consumer(name):          #消费者 5     print("%s 准备吃包子啦!" %name) 6     while True: 7        baozi = yield 8  9        print("包子[%s]来了,被[%s]吃了!" %(baozi,name))10 11 12 def producer(name):      #生产者13     c = consumer('A')14     c2 = consumer('B')15     c.__next__()16     c2.__next__()17     print("老子开始准备做包子啦!")18     for i in range(2):19         time.sleep(1)20         print("做了2个包子!")21         c.send(i)22         c2.send(i)23 24 producer("felix")
生成器—单线程下的并行效果

 

3、迭代器

  •     isinstance([ ],iterable)          #判断列表可不可以迭代   Iterable
  •     可以被 next( )  函数调用并不断返回下一个值的对象称为迭代器  Iterator, 它表示一个惰性计算的序列。

       集合数据类型如list  dict  str  等都是Iterable但不是Iterator ;

      凡是可作用于for循环的对象都是Iterable类型

 

 

三、内置方法

1、内置参数

    详细讲解:https://docs.python.org/3/library/functions.html?highlight=built#ascii 

 

1 #Author : Felix Li 2  3       # 1 4 # a=bytearray("abcde",encoding="utf-8") 5 # 6 # print(a[1]) 7 # a[1]=50 8  9     #210 code='''11 import time12 def consumer(name):          #消费者13     print("%s 准备吃包子啦!" %name)14     while True:15        baozi = yield16 17        print("包子[%s]来了,被[%s]吃了!" %(baozi,name))18 19 20 def producer(name):      #生产者21     c = consumer('A')22     c2 = consumer('B')23     c.__next__()24     c2.__next__()25     print("老子开始准备做包子啦!")26     for i in range(2):27         time.sleep(1)28         print("做了2个包子!")29         c.send(i)30         c2.send(i)31 32 producer("felix")33     '''34 # exec(code)35 36      #337 #print(divmod(3,5))   #商和余数38 39     #4   filter 过滤出想要的元素40 # res=filter(lambda n:n<5,range(10))41 # for i in res:42 #     print(i)43 44     #5   哈希45 #a=hash('123')46 #print(a)47 48    #649 #hex()     #转成16进制50 #oct()     #转成8进制51 52    #7  保留有效数字53 # a=round(3.2131316,6)54 # print(a)55 56    #8   排序57 # a={6:1,8:4,4:-5,-1:258 #59 #   }60 # print(sorted(a.items(),key=lambda x:x[1]))61 # print(a)62 63    #9 一一对应64 a=[1,2,3]65 b=['a','b,','c']66 for i in zip(a,b):67     print(i)
内置函数

 

 

 

四、Json & Pickle数据序列化

1、Json

  •     可跨语言之间交互  C  C++  Python  Java   C#
  •     用于字符串和Python之间转换

     

1 #Author : Felix Li 2    #json序列化     相当于保存一段数据 3 # import json 4 # info={ 5 #     'name':'felix', 6 #     'age':'23' 7 # 8 # } 9 # f=open("test.test","w")10 # f.write( json.dumps(info))11 #12 # f.close()13 14 15 16  #json反序列化     读出之前保存的数据17 import json18 f=open("test.test","r")19 data=json.loads(f.read())20 21 print(data["name"])
Json序列化和反序列化

 

 

2、Pickle

  只能在Python中使用

 

转载地址:http://qrtnmu.baihongyu.com/

你可能感兴趣的文章
洛谷 P2024 [NOI2001]食物链【种类并查集】
查看>>
LeetCode C++ 657. Robot Return to Origin【字符串】简单
查看>>
POJ 1703 Find them, Catch them【种类并查集】
查看>>
POJ 2492 A Bug‘s Life【种类并查集】
查看>>
POJ 2236 Wireless Network【并查集】
查看>>
LeetCode C++ 214. Shortest Palindrome【字符串】困难
查看>>
洛谷 P2580 于是他错误的点名开始了【字典树/Map】
查看>>
HDU 3336 Count the string【KMP的next数组性质】
查看>>
洛谷 P1196 [NOI2002]银河英雄传说【带权并查集】
查看>>
HDU 4825 Xor Sum【01字典树/贪心】(两数最大/最小异或和)
查看>>
洛谷 P4551 最长异或路径【01字典树/贪心】
查看>>
LeetCode C++ 506. Relative Ranks【Sort】简单
查看>>
LeetCode C++ 105. Construct Binary Tree from Preorder and Inorder Traversal【Tree/分治】中等
查看>>
LeetCode C++ 106. Construct Binary Tree from Inorder and Postorder Traversal【Tree/分治】中等
查看>>
LeetCode C++ 504. Base 7【Math】简单
查看>>
LeetCode C++ 563. Binary Tree Tilt【Tree/DFS】简单
查看>>
LeetCode C++ 572. Subtree of Another Tree【Tree/DFS】简单
查看>>
LeetCode C++ 575. Distribute Candies【Greedy】简单
查看>>
LeetCode C++ 680. Valid Palindrome II【String】简单
查看>>
LeetCode C++ 700. Search in a Binary Search Tree【二叉搜索树】简单
查看>>