1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Python100天学习1-15
资料连接
第一天-初识python
1 2 3 4 5 6 7 8 9 10 print ('你好' , '世界' )print ('hello' , 'world' , sep=', ' , end='!' )print ('goodbye, world' , end='!\n' )
第二天-语言元素
1 2 3 4 5 6 7 8 9 10 - chr ():将整数转换成该编码对应的字符串(一个字符)。 - ord ():将字符串(一个字符)转换成对应的编码(整数)。 - int (): 将字符串表示的n进制数字转换为十进制表示 - bin (), oct (), hex (): 将十进制数字转为2 /8 /16 进制字符串表示
# 3. 类型转换
# 4. 运算符及其优先级
运算符
描述
[]
[:]
下标,切片
**
指数
~
+
-
按位取反, 正负号
*
/
%
//
乘,除,模,整除
+
-
加,减
>>
<<
右移,左移
&
按位与
^
|
按位异或,按位或
<=
<
>
>=
小于等于,小于,大于,大于等于
==
!=
等于,不等于
is
is not
身份运算符
in
not in
成员运算符
not
or
and
逻辑运算符
=
+=
-=
*=
/=
%=
//=
**=
&=
`
=^=>>=<<=`
说明: 在实际开发中,如果搞不清楚运算符的优先级,可以使用括号来确保运算的执行顺序。
第三天-分支结构
–
第四天-循环结构
–
第五天-构造程序逻辑
–
第六天-函数和模块的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 可变参数允许传入0 个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple 。 关键字参数允许传入0 个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict 。 如果导入的模块除了定义函数之外还有可以执行代码,那么Python解释器在导入这个模块时就会执行这些代码 if __name__ == '__main__' : def a (): def b ():
第七天-字符串和常用数据结构
字符串函数
可以使用*复制字符串
因此a=[[0] * 3]*5 a里面的list都是同一个地址,修改一个就会修改全部
但是[0] * 3 数字是直接存的对象 修改这个就是直接换了个对象 不糊修改对象的内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 str1 = 'hello, world!' print (len (str1)) print (str1.capitalize()) print (str1.title()) print (str1.upper()) print (str1.find('or' )) print (str1.find('shit' )) print (str1.startswith('He' )) print (str1.startswith('hel' )) print (str1.endswith('!' )) print (str1.center(50 , '*' ))print (str1.rjust(50 , ' ' ))str2 = 'abc123456' print (str2.isdigit()) print (str2.isdecimal()) print (str2.isnumeric()) print (str2.istitle())print (str2.isspace())print (str2.isalpha()) print (str2.isalnum()) str3 = ' jackfrued@126.com ' print (str3)print (str3.strip())print (str3.partition('@' )) print (str3.swapcase())
字符串格式化
1 2 3 4 5 6 7 8 9 10 11 a, b = 5 , 10 print ('%d * %d = %d' % (a, b, a * b))a, b = 5 , 10 print ('{} * {} = {}' .format (a, b, a * b))print ('{0} * {1} = {2}' .format (a, b, a * b))print ('{aaa} * {bbb} = {ccc}' .format (aaa=a, bbb=b, ccc=a * b))a, b = 5 , 10 print (f'{a} * {b} = {a * b} ' )
列表
列表容器中并没有保存真正的对象,它保存的仅仅是对象的引用(堆中的地址)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 list1 = [1 , 3 , 5 , 7 , 100 ] list1.append(200 ) list1.insert(1 , 400 ) list1.extend([1000 , 2000 ]) list1 += [1000 , 2000 ] list1.remove(1234 ) list1.pop(0 ) fruits = [ [66666 ,77777777 ], 'apple' , 'strawberry' , 'waxberry' ] fruits3 = fruits[:4 ] print (fruits3) fruits3[0 ][0 ]=000 fruits3[2 ]='aaaaaaaaa' print (fruits3)print (fruits)
什么时候不用数组
生成器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import sysf = [x ** 2 for x in range (1 , 1000 )] print (sys.getsizeof(f)) f = (x ** 2 for x in range (1 , 1000 )) print (sys.getsizeof(f)) for val in f: print (val) yield :生成函数
元组
元组在创建时间和占用的空间上面都优于列表
集合
字典
序列的抽象基类
MutavleSequence:可变序列抽象基类(setitem,delitem)
Sequence:不可变序列抽象基类
+,+=,extend区别
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 a=[1 ,2 ] print (id (a))a.extend((777 ,)) a+=[666 ] print (id (a))a=a+[666 ] print (id (a))a.append([666 ,777 ]) print (id (a))
可切片对象
1 2 3 4 5 6 7 8 9 10 alist[len (alist):]=[9 ] alist[:0 ]=[1 ,2 ] alist[3 :3 ]=[1 ,2 ]
第八天-面向对象编程基础
python三个知识点:is和==,嵌套列表,类的私有属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 class Test : def __init__ (self, foo ): self.__foo = foo def __bar (self ): print (self.__foo) print ('__bar' ) def main (): test = Test('hello' ) test.__bar() print (test.__foo) test = Test('hello' ) test._Test__bar() print (test._Test__foo) if __name__ == "__main__" : main()
第九天-面向对象进阶
class用于声明一个类,用type创建类
object是所有类的父类,所有类是type的实例
类的属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 class Person (object ): def __init__ (self, name, age ): self._name = name self._age = age @property def name (self ): return self._name @property def age (self ): return self._age @age.setter def age (self, age ): self._age = age class Person (object ): __slots__ = ('_name' , '_age' , '_gender' ) def __init__ (self, name, age ): self._name = name self._age = age Person._gender = '男' Person.sex = '?' person = Person('王大锤' , 22 ) person.sex=66
类的方法
1 2 3 4 5 6 7 8 9 10 11 12 @classmethod def now (cls ): print (cls)
继承和多态
1 2 3 4 5 6 7 8 9 10 11 12 13 from abc import ABCMeta, abstractmethodclass Pet (object , metaclass=ABCMeta): def __init__ (self, nickname ): self._nickname = nickname @abstractmethod def make_voice (self ): pass
定制类-魔法函数(不是继承,python自带)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 def __str__ (self ): return '6666' __repr__ = __str__ class Fib (object ): def __init__ (self ): self.a, self.b = 0 , 1 def __iter__ (self ): return self def __next__ (self ): self.a, self.b = self.b, self.a + self.b if self.a > 100000 : raise StopIteration() return self.a if isinstance (n, int ): if isinstance (n, slice ): class Sample : def __enter__ (self ): print ( "enter" ) return self def __exit__ (self, exc_type,exc_val,exc_tb ): print ( "exit" ) def do_something (self ): print ( "doing something" ) with Sample() as sample: sample.do_something()
如果要获得一个对象的所有属性和方法,可以使用dir()函数
dir('abc')
第十天-图形用户界面和游戏开发
–
第十一天-文件和异常
–
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import jsondata = { 'name' : 'ACME' , 'shares' : 100 , 'price' : 542.23 } json_str = json.dumps(data) data = json.loads(json_str) with open ('data.json' , 'w' ) as f: json.dump(data, f) with open ('data.json' , 'r' ) as f: data = json.load(f)
第十二天-字符串和正则表达式
正则表达式练习
正则表达式规则
函数
说明
compile(pattern, flags=0)
编译正则表达式返回正则表达式对象
match(pattern, string, flags=0)
用正则表达式匹配字符串 成功返回匹配对象 否则返回None
search(pattern, string, flags=0)
搜索字符串中第一次出现正则表达式的模式 成功返回匹配对象 否则返回None
split(pattern, string, maxsplit=0, flags=0)
用正则表达式指定的模式分隔符拆分字符串 返回列表
sub(pattern, repl, string, count=0, flags=0)
用指定的字符串替换原字符串中与正则表达式匹配的模式 可以用count指定替换的次数
fullmatch(pattern, string, flags=0)
match函数的完全匹配(从字符串开头到结尾)版本
findall(pattern, string, flags=0)
查找字符串所有与正则表达式匹配的模式 返回字符串的列表
finditer(pattern, string, flags=0)
查找字符串所有与正则表达式匹配的模式 返回一个迭代器
purge()
清除隐式编译的正则表达式的缓存
re.I / re.IGNORECASE
忽略大小写匹配标记
re.M / re.MULTILINE
多行匹配标记
第十三天-进程和线程
进程线程知识参考操作系统
多进程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 from multiprocessing import Processfrom os import getpidfrom random import randintfrom time import time, sleepdef download_task (filename ): print ('启动下载进程,进程号[%d].' % getpid()) print ('开始下载%s...' % filename) time_to_download = randint(5 , 10 ) sleep(time_to_download) print ('%s下载完成! 耗费了%d秒' % (filename, time_to_download)) def main (): start = time() p1 = Process(target=download_task, args=('Python从入门到住院.pdf' , )) p1.start() p2 = Process(target=download_task, args=('Peking Hot.avi' , )) p2.start() p1.join() p2.join() end = time() print ('总共耗费了%.2f秒.' % (end - start)) if __name__ == '__main__' : main() def main (): start = time() p = Pool(4 ) for i in range (5 ): p.apply_async(download_task, args=(i,)) p.close() p.join() print ('总共耗费了%.2f秒.' % (end - start)) from multiprocessing import Process, Queueimport os, time, randomdef write (q ): print ('Process to write: %s' % os.getpid()) for value in ['A' , 'B' , 'C' ]: print ('Put %s to queue...' % value) q.put(value) time.sleep(random.random()) def read (q ): print ('Process to read: %s' % os.getpid()) while True : value = q.get(True ) print ('Get %s from queue.' % value) if __name__=='__main__' : q = Queue() pw = Process(target=write, args=(q,)) pr = Process(target=read, args=(q,)) pw.start() pr.start() pw.join() pr.terminate() ''' Process to write: 50563 Put A to queue... Process to read: 50564 Get A from queue. Put B to queue... Get B from queue. Put C to queue... Get C from queue. '''
多线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 from random import randintfrom threading import Threadfrom time import time, sleepdef download (filename ): print ('开始下载%s...' % filename) time_to_download = randint(5 , 10 ) sleep(time_to_download) print ('%s下载完成! 耗费了%d秒' % (filename, time_to_download)) def main (): start = time() t1 = Thread(target=download, args=('Python从入门到住院.pdf' ,)) t1.start() t2 = Thread(target=download, args=('Peking Hot.avi' ,)) t2.start() t1.join() t2.join() end = time() print ('总共耗费了%.3f秒' % (end - start)) if __name__ == '__main__' : main() from random import randintfrom threading import Threadfrom time import time, sleepclass DownloadTask (Thread ): def __init__ (self, filename ): super ().__init__() self._filename = filename def run (self ): print ('开始下载%s...' % self._filename) time_to_download = randint(5 , 10 ) sleep(time_to_download) print ('%s下载完成! 耗费了%d秒' % (self._filename, time_to_download)) def main (): start = time() t1 = DownloadTask('Python从入门到住院.pdf' ) t1.start() t2 = DownloadTask('Peking Hot.avi' ) t2.start() t1.join() t2.join() end = time() print ('总共耗费了%.2f秒.' % (end - start)) if __name__ == '__main__' : main() from time import sleepfrom threading import Thread, Lockclass Account (object ): def __init__ (self ): self._balance = 0 self._lock = Lock() def deposit (self, money ): self._lock.acquire() try : new_balance = self._balance + money sleep(0.01 ) self._balance = new_balance finally : self._lock.release() @property def balance (self ): return self._balance class AddMoneyThread (Thread ): def __init__ (self, account, money ): super ().__init__() self._account = account self._money = money def run (self ): self._account.deposit(self._money) def main (): account = Account() threads = [] for _ in range (100 ): t = AddMoneyThread(account, 1 ) threads.append(t) t.start() for t in threads: t.join() print ('账户余额为: ¥%d元' % account.balance) if __name__ == '__main__' : main() from queue import Queue
第十四天-网络编程入门和网络应用开发
计算机网络基础知识补充
发邮件
发短信
网络服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 from socket import socket, SOCK_STREAM, AF_INETfrom base64 import b64encodefrom json import dumpsfrom threading import Threaddef main (): class FileTransferHandler (Thread ): def __init__ (self, cclient ): super ().__init__() self.cclient = cclient def run (self ): my_dict = {} my_dict['filename' ] = 'guido.jpg' my_dict['filedata' ] = data json_str = dumps(my_dict) self.cclient.send(json_str.encode('utf-8' )) self.cclient.close() server = socket() server.bind(('192.168.1.2' , 5566 )) server.listen(512 ) print ('服务器启动开始监听...' ) with open ('guido.jpg' , 'rb' ) as f: data = b64encode(f.read()).decode('utf-8' ) while True : client, addr = server.accept() FileTransferHandler(client).start() if __name__ == '__main__' : main() from socket import socketfrom json import loadsfrom base64 import b64decodedef main (): client = socket() client.connect(('192.168.1.2' , 5566 )) in_data = bytes () data = client.recv(1024 ) while data: in_data += data data = client.recv(1024 ) my_dict = loads(in_data.decode('utf-8' )) filename = my_dict['filename' ] filedata = my_dict['filedata' ].encode('utf-8' ) with open ('/Users/Hao/' + filename, 'wb' ) as f: f.write(b64decode(filedata)) print ('图片已保存.' ) if __name__ == '__main__' : main()
第十五天-图像和办公文档处理
图像
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 >>> from PIL import Image>>> >>> image = Image.open ('./res/guido.jpg' )>>> image.format , image.size, image.mode('JPEG' , (500 , 750 ), 'RGB' ) >>> image.show()>>> image = Image.open ('./res/guido.jpg' )>>> rect = 80 , 20 , 310 , 360 >>> image.crop(rect).show()>>> image = Image.open ('./res/guido.jpg' )>>> size = 128 , 128 >>> image.thumbnail(size)>>> image.show()>>> image1 = Image.open ('./res/luohao.png' )>>> image2 = Image.open ('./res/guido.jpg' )>>> rect = 80 , 20 , 310 , 360 >>> guido_head = image2.crop(rect)>>> width, height = guido_head.size>>> image1.paste(guido_head.resize((int (width / 1.5 ), int (height / 1.5 ))), (172 , 40 ))>>> image = Image.open ('./res/guido.png' )>>> image.rotate(180 ).show()>>> image.transpose(Image.FLIP_LEFT_RIGHT).show()>>> image = Image.open ('./res/guido.jpg' )>>> for x in range (80 , 310 ):... for y in range (20 , 360 ):... image.putpixel((x, y), (128 , 128 , 128 ))... >>> image.show()>>> from PIL import Image, ImageFilter>>> >>> image = Image.open ('./res/guido.jpg' )>>> image.filter (ImageFilter.CONTOUR).show()
Excel
Word
B站视频总结
元类编程
元类:创建类的类
1.动态属性
1 2 3 4 5 6 7 8 9 10 @property修饰 @aaa.setter __getattr__ __getattribute__ getattr (类,属性)==类.属性
2.属性描述符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class IntField : def __get__ ( self, instance,owner ): return self.value def __set__ (self, instance, value ): if not isinstance (value, numbers.Integral): raise ValueError( "int value need" ) if value < 0 : raise ValueError( "positive value need" ) self.value = value def __delete__ (self, instance ): pass class User : age = IntField()
3.类属性取值过程
如果user是某个类的实例,那么user.age(以及等价的getattr(user, ‘age’))首先调用__getattribute__。如果类定义了_getattr_方法,
那么在_getattribute__抛出 AttributeError的时候就会调用到_getattr_,而对于描述符(get )的调用,则是发生在__getattribute__内部的。
user = User(),那么user.age顺序如下:
(1) 如果"age”是出现在user或其基类的__dict__中,且age是data descriptor,那么调用其__get__方法 ,否则
(2) 如果"age"出现在obj的__dict__中,那么直接返回 obj.dict [ ‘age’],否则
(3) 如果"age"出现在User或其基类的__dict__中
(3.1) 如果age是non-data descriptor,那么调用其__get__方法,否则
(3.2) 返回__dict__[ ‘age’]
(4) 如果User有__getattr__方法,调用__getattr__方法,否则
(5) 抛出AttributeError
4.__new__和__init__区别
new传的类本身
init传的对象实例
先进new后进init
new不返回对象,不会进init
5.type动态创建类
type(“类名”,(父类),{属性,函数})
控制类的创建过程
class user(metaclass=自定义元类)
元类编程->封装
6.可迭代,迭代器,生成器
迭代器和迭代序列分离
iter 可迭代
next 迭代器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class company (object ): def _init_ (self, employee_list ): self.employee = employee_list def _iter_ ( self ): return MyIterator( self.employee) class MyIterator (Iterator ) : def _init_ (self, employee_list ): self.iter_list = employee_listself.index = 0 def inext_ (self ): try : word = self.iter_list[ self.index] except IndexError: raise stopIteration self.index +=1 return word
生成器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 def gen_fib (index ): n,a,b = 0 ,0 ,1 while n<index: yie1d b a,b = b,a+b n += 1 for data in gen_fib(10 ): print (data) I PyGenObject gi_frame gi_code 会保存上一次执行的位置和代码
大文件读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 def myreadlines (f, newline ) :buf = "" while True : while newline in buf: pos = buf.index( newline) yield buf[:pos] buf = buf[pos + len (newline) : ] chunk = f.read(4096 *10 ) if not chunk : yield buf break buf += chunk with open ("input.txt" ) as f: for line in myreadlines(f,"{" ): print (line)
7.socket编程
见网络编程
8.多线程
1.GIL
全局解释器锁
python中一个线程对应c语言的一个线程
gil使得同一时刻只有一个线程运行在一个cpu上运行字节码
不能把多个线程映射到多个cpu上
gil会根据执行的字节码行数及时间片释放gil
遇见io操作也会主动释放(适合io频繁)
2.线程同步,通信
多线程实现
使用线程传递函数
继承多线程类,实现run
线程通信
共享变量:不好
Queue:还有其他线程安全的数据结构
线程同步
Lock,RLock
Lock :获取两次就会死锁
RLock :允许多线程环境下多次acquire,但是release要一样的数量
condition :wait()和notify() 等待和唤醒
先等待才能唤醒
把waiter的锁放入一个双端队列
notify把队列弹一个出来释放
with condition 就是获取锁释放锁(默认RLock)
with之后才能wait和notify,wait把condition的锁释放掉
con’t wait on a un-acquire lock
Semaphore :用于控制进入数量的锁
threading.Semaphore(3)
3.线程池&进程池
from concurrent import futures
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 executor = ThreadPoo1Executor(max_workers=1 ) task1 = executor. submit(get_htm1,(3 )) task2 = executor. submit(get_htm1,(2 )) task1.done() task1.result() urls = [3 ,2 ,4 ] all_task = [executor. submit(get_html,(url)) for url in urls] for future in as_completed(all_task): data = future.result() print ( "get ipage success" .format (data)) for data in executor.map (get_html, urls): print ( "get {fpage" .format (data)) wait()
进程适合计算密集
线程适合io密集
父进程和子进程各有数据
子进程会把创建进程下面的代码单独运行一遍
ProcessPoolExecutor用的multiprocessing
不能用queue.Queue
不能用共享变量
from queue import Queue
from multiprocessing import Queue
from multiprocessing.Manager import Queue
#Manager 有很多数据结构
pipe只能用于两个进程
性能高于Queue
9.IO复用
并发
并发是指一个时间段内有几个程序在同一个cpu运行,但是任意时刻只有一个程序在cpu上运行
并行
并行是指任意时刻点上,有多个程序同时运行在多个cpu
同步
同步是指代码调用IO操作时必须等待IO操作完成才返
回的调用方式。
异步
异步是指代码调用IO操作时,不必等IO操作完成就返回的调用方式。
阻塞
阻塞是指调用函数时候当前线程被挂起。
非阻塞
非阻塞是指调用函数时候当前线程不会被挂起,而是立即返回。
10.回调协程
11.asynch await
12.事件循环