魔力Python——我踩过的各种坑
Posted 流云封心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了魔力Python——我踩过的各种坑相关的知识,希望对你有一定的参考价值。
1.函数与内置函数
def func(a=1, b=2, l=[]): l.append(a + b) print(l) func(1,2) func(3,4,[]) func(5,6) #结果: #[3] #[7] #[3, 11]
filter:
lst = filter(lambda n:n%3 == 1,range(10)) print(len(list(lst))) print(len(list(lst))) #结果: #3 #0 # filter返回的是迭代对象, 这个迭代器只能迭代一次(list(lst)),迭代完成就完了. 第二次(list(lst)),执行返回的是空. # 但如果你把结果做为list放到内存里, 就没有这个问题了,只是如果list很大的话,内存占用多,效率会下降,好的做是把这些操作串在一起, 一次完成.
2.迭代器,生成器与装饰器
def Generator(): value = yield 1 yield value gen = Generator() print(gen.send(1)) #结果: #报错:TypeError: can\'t send non-None value to a just-started generator #解决方法:第一个用next接收,接下来再用send
v = [lambda :x for x in range(10)] print(v) # print(v[0]) # print(v[0]()) v = (lambda :x for x in range(10)) print(v) for i in range(10): print(v.__next__()()) print(v[0]) #最后一个print报错,TypeError: \'generator\' object is not subscriptable. #原因:第二个生成的v实际上是生成器(此处要注意生成器的两种生成手段,一个是如此生成,另一个是定义出来的用yield挂起值),用v.__next__导出的是函数,此时调用发现从0到9依次输出.而生成器怎么可能像列表那样操作呢? #PS:生成器两种写法: #1.只要把一个列表生成式的[]改成(),就创建了一个generator #2.如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator
装饰器的典型错误:
flag = True def wrapper(func): def inner(*args, **kwargs): if flag: ret = func(*args, **kwargs) return ret return inner @wrapper def wahaha(): print(\'wahaha\') return True flag = False ret = wahaha() print(ret) #输出结果是None,你能想到么?因为里面关了,所以直接不走了,输出none.并不是像想象中的走主函数的语句块,不然装饰器意义何在呢?就是要在装饰器里面调用的呀!
3.正则表达式与re模块
demo1: import re ret = re.search(r\'<(w+)>(\\w+)<(\\\\\\w+)>\',r\'<title>qqxing<\\title>\') print(ret.group()) demo2: import re ret = re.search(r\'<(\\w+)>(\\w+)<(\\\\w+)>\',r\'<title>qqxing<\\title>\') print(ret.group()) #demo1和demo2错误相同. #AttributeError: \'NoneType\' object has no attribute \'group\' #解决方案:demo1应该是\\w+ ; demo2应该是\\\\\\ demo3: import re ret = re.search(r\'<(?P<tab1>\\w+)>(?P<content>\\w+)<(\\\\\\w+)>\',r\'<title>qqxing<\\title>\') print(ret.group(\'<content>\')) #IndexError: no such group #解决方案:去掉<>
demo4:
import re
ret = re.search(\'<(?P<tag>\\w+)>(\\w+)<\\\\(?P=<tag>)>\',r\'<h1>wahaha<\\h2><\\h1>\')
print(ret.group())
#sre_constants.error: unbalanced parenthesis at position 26
#解决方案:第一个前面加个r,即r\'<(?P<tag>\\w+)>.*?<\\\\(?P=tag)>\'
4.面对对象
class Goods: def __init__(self,name,price,number): self.__name = name self.price = price self.number = number def pay(self): print(self.__name) print(self.price) def __add__thing(self): print(\'ok\') apple = Goods(\'apple\',5,10) print(apple.price) print(apple.number) # 报错!!!print(apple.__name)#apple.__name调用不出来#AttributeError: \'Goods\' object has no attribute \'__name\' print(apple.__dict__) print(apple._Goods__name)#_类名__属性名才能调用出来 apple.pay() # 报错!!! apple.__add__thing#AttributeError: \'Goods\' object has no attribute \'__add__thing\' print(apple._Goods__add__thing)#类方法调用情况<bound method Goods.__add__thing of <__main__.Goods object at 0x00000000023D7E80>> apple._Goods__add__thing()#正常输出
5.异常
#demo1:
with open(\'course_st_info\',\'rb\')as f: print(pickle.load(f)) #由于之前没有该文件,所以报错. #报错内容:EOFError: Ran out of input #修正结果 try: with open(\'course_st_info\',\'rb\')as f: print(pickle.load(f)) except EOFError: pass
#demo2:
while 1:
try:
with open(\'course_all_info\', \'ab\')as f:
pickle.load(f)
except EOFError:
break
#报错内容:io.UnsupportedOperation: read
#原因:读取格式不对
#解决方案:将ab改为rb.
6. 网络编程
#server import socket sk = socket.socket() sk.bind((\'127.0.0.1\',9001)) while 1: conn,addr = sk.accept() while 1: username = \'smith\' password = \'123\' usn = conn.recv(1024).decode(\'utf8\') psw = conn.recv(1024).decode(\'utf8\') if usn ==username and psw == password: msg = \'登录成功\' else: msg = \'登录失败\' conn.send(msg.encode(\'utf8\')) conn.close() sk.close() #报错:OSError: [WinError 10022] 提供了一个无效的参数。 #在sk.bind((\'127.0.0.1\',9001))下面写sk.listen() #当缺少监听的时候接收本来就是不可能的事情 #client import socket sk = socket.socket() sk.connect(\'127.0.0.1\',9001) while 1: usn1 = input(\'请输入账号:\').strip() psw1 = input(\'请输入密码:\').strip() sk.send(usn1.encode(\'utf8\')) sk.send(psw1.encode(\'utf8\')) msg1 = sk.recv(1024).decode(\'utf8\') print(msg1) if \'成功\' in msg1:break sk.close() #报错:TypeError: connect() takes exactly one argument (2 given) #这种错误一般是sk.connect处. #sk.connect后面应该跟元组,所以是sk.connect((\'127.0.0.1\',9001))
import socket sk = socket.socket(socket.SOCK_DGRAM) server_addr = (\'127.0.0.1\', 9001) while 1: content = input(\'>>>\') sk.sendto(content.encode(\'utf8\'), server_addr) msg, _ = sk.recvfrom(1024) print(msg.decode(\'utf8\')) sk.close() #OSError: [WinError 10057] 由于套接字没有连接并且(当使用一个 sendto 调用发送数据报套接字时)没有提供地址,发送或接收数据的请求没有被接受。 #原因:sk = socket.socket(type = socket.SOCK_DGRAM)
#server: import json import socket import hashlib import struct def get_sha1(username,password): sha1 = hashlib.sha1(username.encode(\'utf8\')) sha1.update(password.encode(\'utf8\')) return sha1.hexdigest() def get_userinfo(filename_userinfo): with open(filename_userinfo, encoding=\'utf8\') as f: for line in f.readlines(): user,pwd = line.strip().split(\'|\') yield user,pwd sk = socket.socket() sk.bind((\'127.0.0.1\',9001)) sk.listen() conn,addr = sk.accept() flag = 1 while flag: num = conn.recv(4) num = struct.unpack(\'i\', num)[0] bytes_dic1 = conn.recv(num) str_dic1 = bytes_dic1.decode(\'utf8\') dic1 = json.loads(str_dic1) dic1[\'password\'] = get_sha1(dic1[\'username\'], dic1[\'password\']) for user,pwd in read: if dic1[\'username\'] == user and dic1[\'password\'] == pwd: bytes_msg = \'登录成功\'.encode(\'utf8\') struct_len = struct.pack(\'i\',len(bytes_msg)) conn.send(struct_len) conn.send(bytes_msg) flag = 0 break else: flag += 1 if flag == 4: bytes_msg = \'登录失败,请明天再试\'.encode(\'utf8\') struct_len = struct.pack(\'i\', len(bytes_msg)) conn.send(struct_len) conn.send(bytes_msg) conn.close() bytes_msg = \'登录失败,请明天再试\'.encode(\'utf8\') struct_len = struct.pack(\'i\', len(bytes_msg)) conn.send(struct_len) conn.send(bytes_msg) conn.close() sk.close() #client: import json import socket import hashlib import struct def get_md5(username, password): md5 = hashlib.md5(username.encode(\'utf8\')) md5.update(password.encode(\'utf8\')) return md5.hexdigest() for i in range(3): username = input(\'用户名:\').strip() password = input(\'密 码:\').strip() sk = socket.socket() sk.connect((\'127.0.0.1\', 9001)) password = get_md5(username, password) dic1 = {\'username\': username, \'password\': password} str_dic1 = json.dumps(dic1) bytes_dic1 = str_dic1.encode(\'utf8\') bytes_len = struct.pack(\'i\', len(bytes_dic1)) sk.send(bytes_len) sk.send(bytes_dic1) num = sk.recv(4) num = struct.unpack(\'i\',num)[0] bytes_msg = sk.recv(num) print(bytes_msg.decode(\'utf8\')) sk.close() #报错:num = struct.unpack(\'i\', num)[0] #struct.error: unpack requires a buffer of 4 bytes #原因:经查看是循环时候报错,由此推出是因为client端未循环输入username和password的问题.
#报错:非套接字OSError: [WinError 10038] 在一个非套接字上尝试了一个操作。
#原因:查看是否进行了conn.close()但还是在进行连接.
7.MySQL
ERROR 1054(42S22):Unknown column \'smith\' in \'field list\'
解决方案:把变量加上引号变为字符串即可.
8.Django
报错: \'Did you install mysqlclient or MySQL-python?\' % e django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named \'MySQLdb\'. Did you install mysqlclient or MySQL-python?
解决方案:忘配置与settings同级的__init__的文件了.写如下:
import pymysql pymysql.install_as_MySQLdb()
9.通用
9.1 编码问题
table1 = pd.read_excel(r"C:\\Users\\Administrator\\Desktop\\数据1.xls")
table2 = pd.read_excel(r"C:\\Users\\Administrator\\Desktop\\trans.xls")
(unicode error) \'unicodeescape\' codec can\'t decode bytes in position 2-3: truncated \\UXXXXXXXX escape
解决方法:记得在路径处加r. 避免转义.
以上是关于魔力Python——我踩过的各种坑的主要内容,如果未能解决你的问题,请参考以下文章