1 Star 0 Fork 0

小黑 / use_python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
skill.md 2.72 KB
一键复制 编辑 原始数据 按行查看 历史
小黑 提交于 2020-05-20 11:30 . update

try / except 不滥用

在使用时,如果 except 后没跟期望的错误时,
默认会将所有的错误均捕获,后期维护较难,且不能准确定位问题

不推荐的写法

import requests

try:
    resp = requests.get("http://some.domain.com", timeout=1)
    print(resp.text.encode("utf-8"))
except:
    # 报错就退出
    print("请求失败")

推荐的写法

import requests

try:
    resp = requests.get("http://some.domain.com", timeout=1)
    print(resp.text.encode("utf-8"))
except requests.exceptions.SSLError:
    # 请求的地址证书错误
    print("ssl error")
except requests.exceptions.ProxyError:
    # 代理错误
    print("proxy error")

善用 with 语句

读取、写入文件时使用,不用显示地调用关闭, 当程序运行出了 with 块时,会自动调用对象的 exit 方法, 当不知何时安全关闭时,可以采用该方式。 任何提供 enter() 和__exit__() 方法的对象均可调用

# 读文件
with open("xxx.py", "r") as f:
    block = f.read()
    print(block)

# 写文件
with open("xxx.py", "w") as f:
    f.write("hello world")

# 下载大文件
import requests
resp = requests.get("http://some.domain.com", stream=True)
with open("file_path", "wb") as f:
    for chunk in resp.iter_content(chunk_size=512):
        if chunk:
            f.write(chunk)

优雅地交换变量

# 一般写法
a = 1
b = 2
# 交换
tmp = a
a = b
b = tmp


# 优雅写法
a = 1
b = 2
a, b = b, a

将 list 对象中的字符串合并,并用特定字符衔接

a = ["i", "love", "python"]
print("@".join(a))
# 会打印出 i@love@python
print(" ".join(a))
# 会打印出 i love python
print("".join(a))
# 会打印出 ilovepython

常见引用变量的坑

def add_list1(p):
    p = p + [1]
p1 = [1,2,3]
add_list1(p1)
print(p1)
# >>> [1, 2, 3]

def add_list2(p):
    p += [1]
p2 = [1,2,3]
add_list2(p2)
print(p2)
# >>>[1, 2, 3, 1]

# 这主要是由于 "=" 操作符会新建一个新的变量保存赋值结果,
# 然后再把引用名指向“=”左边,即修改了原来的p引用,
# 使p成为指向新赋值变量的引用。而+=不会,
# 直接修改了原来p引用的内容,
# 事实上+=和=在python内部使用了不同的实现函数。
# 引用复制的坑

a = [1, 2, 3]
b = a
a[0] = 3
print(a)
# >>> [3, 2, 3]
print(b)
# >>> [3, 2, 3]

# 当引用的对象是 list、 dict 时,直接赋值均为 弱引用

# 要想完全拷贝,而不是引用调用,可以采用如下方法:
# 通用方案使用 copy.deepcopy 完全拷贝对象使用
import copy
a = [1, 2, 3]
b = copy.deepcopy(a)
a[0] = 3
print(a)
# >>> [3, 2, 3]
print(b)
# >>> [1, 2, 3]
Python
1
https://gitee.com/xiaohei181/use_python.git
git@gitee.com:xiaohei181/use_python.git
xiaohei181
use_python
use_python
master

搜索帮助