13518219792

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

很全面的Python重点知识汇总,建议收藏!

 这是一份来自于 SegmentFault 上的开发者 @二十一 总结的 Python 重点。由于总结了太多的东西,所以篇幅有点长,这也是作者"缝缝补补"总结了好久的东西。

Py2 VS Py3

 
 
 
 
  1. #枚举的注意事项  
  2. from enum import Enum  
  3. class COLOR(Enum):  
  4.     YELLOW=1  
  5. #YELLOW=2#会报错  
  6.     GREEN=1#不会报错,GREEN可以看作是YELLOW的别名  
  7.     BLACK=3  
  8.     RED=4  
  9. print(COLOR.GREEN)#COLOR.YELLOW,还是会打印出YELLOW  
  10. for i in COLOR:#遍历一下COLOR并不会有GREEN  
  11.     print(i)  
  12. #COLOR.YELLOW\nCOLOR.BLACK\nCOLOR.RED\n怎么把别名遍历出来  
  13. for i in COLOR.__members__.items():  
  14.     print(i)  
  15. # output:('YELLOW', )\n('GREEN', )\n('BLACK', )\n('RED', )  
  16. for i in COLOR.__members__:  
  17.     print(i)  
  18. # output:YELLOW\nGREEN\nBLACK\nRED  
  19. #枚举转换  
  20. #最好在数据库存取使用枚举的数值而不是使用标签名字字符串  
  21. #在代码里面使用枚举类  
  22. a=1  
  23. print(COLOR(a))# output:COLOR.YELLOW 

py2/3 转换工具

常用的库

不常用但很重要的库

 
 
 
 
  1. def isLen(strString):  
  2.         #还是应该使用三元表达式,更快  
  3.         return True if len(strString)>6 else False  
  4.     def isLen1(strString):  
  5.         #这里注意false和true的位置  
  6.         return [False,True][len(strString)>6]  
  7.     import timeit  
  8.     print(timeit.timeit('isLen1("5fsdfsdfsaf")',setup="from __main__ import isLen1"))  
  9.     print(timeit.timeit('isLen("5fsdfsdfsaf")',setup="from __main__ import isLen")) 
 
 
 
 
  1. import types  
  2.     types.coroutine #相当于实现了__await__ 
 
 
 
 
  1. import html  
  2.     html.escape("

    I'm Jim

    ") # output:'<h1>I'm Jim</h1>'  
  3.     html.unescape('<h1>I'm Jim</h1>') # 

    I'm Jim

     
 
 
 
 
  1. from concurrent.futures import ThreadPoolExecutor  
  2. pool = ThreadPoolExecutor()  
  3. task = pool.submit(函数名,(参数)) #此方法不会阻塞,会立即返回  
  4. task.done()#查看任务执行是否完成  
  5. task.result()#阻塞的方法,查看任务返回值  
  6. task.cancel()#取消未执行的任务,返回True或False,取消成功返回True  
  7. task.add_done_callback()#回调函数  
  8. task.running()#是否正在执行     task就是一个Future对象  
  9. for data in pool.map(函数,参数列表):#返回已经完成的任务结果列表,根据参数顺序执行  
  10.     print(返回任务完成得执行结果data) 
  11. from concurrent.futures import as_completed  
  12. as_completed(任务列表)#返回已经完成的任务列表,完成一个执行一个  
  13. wait(任务列表,return_when=条件)#根据条件进行阻塞主线程,有四个条件 
 
 
 
 
  1. future=asyncio.ensure_future(协程)  等于后面的方式  future=loop.create_task(协程)  
  2. future.add_done_callback()添加一个完成后的回调函数  
  3. loop.run_until_complete(future)  
  4. future.result()查看写成返回结果  
  5. asyncio.wait()接受一个可迭代的协程对象  
  6. asynicio.gather(*可迭代对象,*可迭代对象)    两者结果相同,但gather可以批量取消,gather对象.cancel()  
  7. 一个线程中只有一个loop 
  8. 在loop.stop时一定要loop.run_forever()否则会报错  
  9. loop.run_forever()可以执行非协程  
  10. 最后执行finally模块中 loop.close()  
  11. asyncio.Task.all_tasks()拿到所有任务 然后依次迭代并使用任务.cancel()取消 
  12. 偏函数partial(函数,参数)把函数包装成另一个函数名  其参数必须放在定义函数的前面  
  13. loop.call_soon(函数,参数)  
  14. call_soon_threadsafe()线程安全    
  15. loop.call_later(时间,函数,参数)  
  16. 在同一代码块中call_soon优先执行,然后多个later根据时间的升序进行执行  
  17. 如果非要运行有阻塞的代码  
  18. 使用loop.run_in_executor(executor,函数,参数)包装成一个多线程,然后放入到一个task列表中,通过wait(task列表)来运行 
  19. 通过asyncio实现http  
  20. reader,writer=await asyncio.open_connection(host,port)  
  21. writer.writer()发送请求  
  22. async for data in reader:  
  23.     datadata=data.decode("utf-8")  
  24.     list.append(data)  
  25. 然后list中存储的就是html  
  26. as_completed(tasks)完成一个返回一个,返回的是一个可迭代对象    
  27. 协程锁  
  28. async with Lock(): 

Python进阶

 
 
 
 
  1. from multiprocessing import Manager,Process  
  2. def add_data(p_dict, key, value):  
  3.     p_dict[key] = value 
  4. if __name__ == "__main__":  
  5.     progress_dict = Manager().dict()  
  6.     from queue import PriorityQueue  
  7.     first_progress = Process(target=add_data, args=(progress_dict, "bobby1", 22))  
  8.     second_progress = Process(target=add_data, args=(progress_dict, "bobby2", 23))  
  9.     first_progress.start()  
  10.     second_progress.start()  
  11.     first_progress.join()  
  12.     second_progress.join() 
  13.     print(progress_dict) 
 
 
 
 
  1. from multiprocessing import Pipe,Process  
  2. #pipe的性能高于queue  
  3. def producer(pipe):  
  4.     pipe.send("bobby")  
  5. def consumer(pipe):  
  6.     print(pipe.recv()) 
  7. if __name__ == "__main__":  
  8.     recevie_pipe, send_pipe = Pipe()  
  9.     #pipe只能适用于两个进程  
  10.     my_producer= Process(target=producer, args=(send_pipe, ))  
  11.     my_consumer = Process(target=consumer, args=(recevie_pipe,))  
  12.     my_producer.start()  
  13.     my_consumer.start()  
  14.     my_producer.join()  
  15.     my_consumer.join() 
 
 
 
 
  1. from multiprocessing import Queue,Process  
  2. def producer(queue):  
  3.     queue.put("a")  
  4.     time.sleep(2)  
  5. def consumer(queue):  
  6.     time.sleep(2)  
  7.     data = queue.get()  
  8.     print(data)  
  9. if __name__ == "__main__":  
  10.     queue = Queue(10)  
  11.     my_producer = Process(target=producer, args=(queue,))  
  12.     my_consumer = Process(target=consumer, args=(queue,))  
  13.     my_producer.start()  
  14.     my_consumer.start()  
  15.     my_producer.join()  
  16.     my_consumer.join() 
 
 
 
 
  1. def producer(queue):  
  2.     queue.put("a")  
  3.     time.sleep(2)  
  4. def consumer(queue):  
  5.     time.sleep(2)  
  6.     data = queue.get()  
  7.     print(data)  
  8. if __name__ == "__main__":  
  9.     queue = Manager().Queue(10)  
  10.     pool = Pool(2)  
  11.     pool.apply_async(producer, args=(queue,))  
  12.     pool.apply_async(consumer, args=(queue,)) 
  13.     pool.close()  
  14.     pool.join() 
 
 
 
 
  1. # 方法一  
  2.     True in [i in s for i in [a,b,c]]  
  3.     # 方法二  
  4.     any(i in s for i in [a,b,c])  
  5.     # 方法三  
  6.     list(filter(lambda x:x in s,[a,b,c])) 
 
 
 
 
  1. import sys  
  2.     sys.getdefaultencoding()    # setdefaultencodeing()设置系统编码方式 
 
 
 
 
  1. class A(dict):  
  2.     def __getattr__(self,value):#当访问属性不存在的时候返回  
  3.         return 2  
  4.     def __getattribute__(self,item):#屏蔽所有的元素访问  
  5.         return item 
 
 
 
 
  1. print([[x for x in range(1,101)][i:i+3] for i in range(0,100,3)]) 
 
 
 
 
  1. type.__bases__  #(,)  
  2. object.__bases__    #()  
  3. type(object)    #    
 
 
 
 
  1. class Yuan(type):  
  2.         def __new__(cls,name,base,attr,*args,**kwargs):  
  3.             return type(name,base,attr,*args,**kwargs)  
  4.     class MyClass(metaclass=Yuan):  
  5.         pass 
 
 
 
 
  1. class MyTest(unittest.TestCase):  
  2.         def tearDown(self):# 每个测试用例执行前执行  
  3.             print('本方法开始测试了')  
  4.         def setUp(self):# 每个测试用例执行之前做操作  
  5.             print('本方法测试结束') 
  6.         @classmethod  
  7.         def tearDownClass(self):# 必须使用 @ classmethod装饰器, 所有test运行完后运行一次  
  8.             print('开始测试')  
  9.         @classmethod  
  10.         def setUpClass(self):# 必须使用@classmethod 装饰器,所有test运行前运行一次  
  11.             print('结束测试') 
  12.         def test_a_run(self):  
  13.             self.assertEqual(1, 1)  # 测试用例 
 
 
 
 
  1. for gevent import monkey  
  2.     monkey.patch_all()  #将代码中所有的阻塞方法都进行修改,可以指定具体要修改的方法  
 
 
 
 
  1. co_flags = func.__code__.co_flags  
  2.    # 检查是否是协程  
  3.    if co_flags & 0x180:  
  4.        return func  
  5.    # 检查是否是生成器  
  6.    if co_flags & 0x20:  
  7.        return func 
 
 
 
 
  1. #一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。  
  2. #请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?  
  3. #方式一: 
  4. fib = lambda n: n if n <= 2 else fib(n - 1) + fib(n - 2)  
  5. #方式二:  
  6. def fib(n):  
  7.     a, b = 0, 1  
  8.     for _ in range(n):  
  9.         a, bb = b, a + b  
  10.     return b  
  11. #一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。  
  12. fib = lambda n: n if n < 2 else 2 * fib(n - 1) 
 
 
 
 
  1. import os  
  2.     os.getenv(env_name,None)#获取环境变量如果不存在为None 
 
 
 
 
  1. #查看分代回收触发  
  2.     import gc  
  3.     gc.get_threshold()  #output:(700, 10, 10) 
 
 
 
 
  1. def conver_bin(num):  
  2.         if num == 0:  
  3.             return num  
  4.         re = []  
  5.         while num:  
  6.             num, rem = divmod(num,2)  
  7.             re.append(str(rem))  
  8.         return "".join(reversed(re))  
  9.     conver_bin(10) 
 
 
 
 
  1. list1 = ['A', 'B', 'C', 'D']  
  2.   # 方法一  
  3.   for i in list1:  
  4.       globals()[i] = []   # 可以用于实现python版反射  
  5.   # 方法二  
  6.   for i in list1:  
  7.       exec(f'{i} = []')   # exec执行字符串语句 
 
 
 
 
  1. # bytearray是可变的,bytes是不可变的,memoryview不会产生新切片和对象  
  2.     a = 'aaaaaa'  
  3.     ma = memoryview(a)  
  4.     ma.readonly  # 只读的memoryview  
  5.     mb = ma[:2]  # 不会产生新的字符串  
  6.     a = bytearray('aaaaaa')  
  7.     ma = memoryview(a)  
  8.     ma.readonly  # 可写的memoryview  
  9.     mb = ma[:2]      # 不会会产生新的bytearray  
  10.     mb[:2] = 'bb'    # 对mb的改动就是对ma的改动 
 
 
 
 
  1. # 代码中出现...省略号的现象就是一个Ellipsis对象  
  2. L = [1,2,3]  
  3. L.append(L)  
  4. print(L)    # output:[1,2,3,[…]] 
 
 
 
 
  1. class lazy(object):  
  2.         def __init__(self, func):  
  3.             self.func = func  
  4.         def __get__(self, instance, cls):  
  5.             val = self.func(instance)    #其相当于执行的area(c),c为下面的Circle对象  
  6.             setattr(instance, self.func.__name__, val)  
  7.             return val`  
  8.     class Circle(object):  
  9.         def __init__(self, radius):  
  10.             self.radius = radius  
  11.         @lazy  
  12.         def area(self):  
  13.             print('evalute')  
  14.             return 3.14 * self.radius ** 2 
 
 
 
 
  1. all_files = []    
  2. def getAllFiles(directory_path):  
  3.     import os                                     
  4.      for sChild in os.listdir(directory_path):               
  5.          sChildPath = os.path.join(directory_path,sChild) 
  6.          if os.path.isdir(sChildPath): 
  7.              getAllFiles(sChildPath) 
  8.          else: 
  9.             all_files.append(sChildPath)  
  10.     return all_files 
 
 
 
 
  1. #secure_filename将字符串转化为安全的文件名  
  2. from werkzeug import secure_filename  
  3. secure_filename("My cool movie.mov") # output:My_cool_movie.mov  
  4. secure_filename("../../../etc/passwd") # output:etc_passwd  
  5. secure_filename(u'i contain cool \xfcml\xe4uts.txt') # output:i_contain_cool_umlauts.txt 
 
 
 
 
  1. from datetime import datetime  
  2. datetime.now().strftime("%Y-%m-%d")  
  3. import time  
  4. #这里只有localtime可以被格式化,time是不能格式化的  
  5. time.strftime("%Y-%m-%d",time.localtime()) 
 
 
 
 
  1. # 会报错,但是tuple的值会改变,因为t[1]id没有发生变化  
  2. t=(1,[2,3])  
  3. t[1]+=[4,5]  
  4. # t[1]使用append\extend方法并不会报错,并可以成功执行 
 
 
 
 
  1. class Mydict(dict):  
  2.     def __missing__(self,key): # 当Mydict使用切片访问属性不存在的时候返回的值  
  3.         return key 
 
 
 
 
  1. # +不能用来连接列表和元祖,而+=可以(通过iadd实现,内部实现方式为extends(),所以可以增加元组),+会创建新对象  
  2. #不可变对象没有__iadd__方法,所以直接使用的是__add__方法,因此元祖可以使用+=进行元祖之间的相加 
 
 
 
 
  1. dict.fromkeys(['jim','han'],21) # output:{'jim': 21, 'han': 21} 

网络知识

 
 
 
 
  1. 204 No Content //请求成功处理,没有实体的主体返回,一般用来表示删除成功  
  2.     206 Partial Content //Get范围请求已成功处理  
  3.     303 See Other //临时重定向,期望使用get定向获取  
  4.     304 Not Modified //请求缓存资源  
  5.     307 Temporary Redirect //临时重定向,Post不会变成Get  
  6.     401 Unauthorized //认证失败  
  7.     403 Forbidden //资源请求被拒绝  
  8.     400 //请求参数错误  
  9.     201 //添加或更改成功  
  10.     503 //服务器维护或者超负载 
 
 
 
 
  1. # environ:一个包含所有HTTP请求信息的dict对象  
  2.     # start_response:一个发送HTTP响应的函数  
  3.     def application(environ, start_response):  
  4.         start_response('200 OK', [('Content-Type', 'text/html')])  
  5.         return '

    Hello, web!

MySQL

          https://segmentfault.com/a/1190000018371218

          https://segmentfault.com/a/1190000018380324

           http://ningning.today/2017/02/13/database/深入浅出mysql/

例如:

 
 
 
 
  1. select id from t where substring(name,1,3) = 'abc' – name;  
  2. 以abc开头的,应改成: 
  3. select id from t where name like 'abc%'   
  4. 例如:  
  5. select id from t where datediff(day, createdate, '2005-11-30') = 0 – '2005-11-30';  
  6. 应改为: 
 
 
 
 
  1. 如:  
  2. select id from t where num/2 = 100   
  3. 应改为:  
  4. select id from t where num = 100*2; 

Redis命令总结

Linux

设计模式

单例模式  

 
 
 
 
  1. # 方式一  
  2.     def Single(cls,*args,**kwargs):  
  3.         instances = {}  
  4.         def get_instance (*args, **kwargs):  
  5. 名称栏目:很全面的Python重点知识汇总,建议收藏!
    本文链接:http://cdbrznjsb.com/article/dhhjgos.html

其他资讯

让你的专属顾问为你服务